r - 将嵌套循环的结果添加到 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
我将不胜感激任何帮助识别我的代码中的错误。
解决方案
您可以使用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])
)
}
我确信有更清洁的方法来解决问题,但这应该会给你一些想法。
推荐阅读
- amazon-web-services - 捕获 S3 文件下载开始和结束时间以及其他详细信息
- azure - 如何通过 Azure DevOps 从 Azure 中删除存储帐户
- xamarin - 带有 Xamarin 应用程序的 VS2017 和 Win7 中的命名空间问题?
- java - Maven 无法使用 OpenJDK 11 找到 jaxb-api,即使它存在于存储库中
- javascript - 画布触觉 JS
- docker - Docker 没有重新启动
- c# - 全尺寸图像的用户控件
- node.js - 尝试在生产模式下编译时 webpack 失败
- javascript - 如何在 JavaScript 生成的输出中包含 PHP 文件的内容?
- sharepoint - 如何根据另一个列表更新一个 SharePoint 2013 列表中的字段