首页 > 解决方案 > 将嵌套循环的结果添加到 R 中的数据框行中

问题描述

我正在尝试创建一个循环,以便可以在列表中列出下面循环中的结果。

如您所见,我的数据是从两个人的 10 个电极中取出的,我想比较每一对电极并从中建模一个广义线性模型,这就是嵌套循环派上用场的地方。我使用了在循环线程中填充 R 中的数据帧中的说明,然后我的代码就出来了。问题是,它不会写多于一行,也不会迭代。

dfnew <- as.data.frame(matrix(NA,0,4))
x <- c("elec1", "elec2", "estimate", "pvalue")
colnames(dfnew) <- x

for (i in 1:100){ #total numbers of coincidences between the electrodes from both individuals
for (j in 1:10){ #electrodes from individual 1
  for (k in 1:10){ #electrodes from individual 2

A <- subset(dyad_data, elec1 == j & elec2 == k)

B1 <- glm(response ~ dyad , data = A, family=Gamma(link = "inverse"))

dfnew[i,1] <- print(j) #it prints the identifier of electrode from individual 1
dfnew[i,2] <- print(k) #it prints the identifier of electrode from individual 2
dfnew[i,3] <- coef(summary(B1))[2, 3]
dfnew[i,4] <- coef(summary(B1))[2, 4]


}}}

问题是结果似乎覆盖了前一行,它没有添加一行,但它保持在同一行。

这就是我的 A 子集与个体 1 的电极 1 和个体 2 的电极 1 的样子,因此您可以查看我的数据类型:

> head(A)
     Elec1 Elec2 Dyad response
187  1     1     1    0.09312585
188  1     1     2    0.09561456
189  1     1     3    0.03530233
2374 1     1     4    0.08787908
2375 1     1     5    0.15917199
2376 1     1     6    0.02174757

我将不胜感激任何帮助识别我的代码中的错误。

标签: rdataframenested-loops

解决方案


您可以使用bind_rows将行附加到数据框的底部,或rbind使用矩阵:

library(dplyr)

df <- 
  tibble::tribble(
  ~Elec1, ~Elec2, ~Dyad,  ~response,
      1,      1,     1, 0.09312585,
      1,      1,     2, 0.09561456,
      1,      1,     3, 0.03530233,
      1,      1,     4, 0.08787908,
      1,      1,     5, 0.15917199,
      1,      1,     6, 0.02174757,
      1,      2,     1, 0.2,
      1,      2,     2, 0.3,
      1,      2,     3, 0.23,
      1,      2,     4, 0.43,
      1,      2,     5, 0.44,
      1,      2,     6, 0.55
  )

summary_df <- 
  tribble(~Elec1, ~Elec2, ~estimate, ~pvalue)

distinct_pairs <- 
  df %>% 
  select(Elec1, Elec2) %>% 
  distinct()

for (i in 1:nrow(distinct_pairs)) {
  model_coefs <- 
    df %>% 
    inner_join(distinct_pairs[i, ], by = c("Elec1", "Elec2")) %>% 
    glm(data = ., formula = response ~ Dyad, family = Gamma(link = "inverse")) %>% 
    summary() %>% 
    coef()

  summary_df <-
    summary_df %>% 
    bind_rows(
      c(distinct_pairs[i, ], 
        estimate = model_coefs[2, 3], 
        pvalue = model_coefs[2, 4])
    )
}

我确信有更清洁的方法来解决问题,但这应该会给你一些想法。


推荐阅读