在 R 中,使用循环(或 while 或 for)来执行在两个不同时间测量的变量之间的相关性测试

In R, use loop (or while or for) to perfom correlation tests between variables measured at two different times

我已经尝试在此处调整此 但它不起作用。

假设我有这个 ds

ds <- data.frame(ige_1 = c(0,1,2,3),
                 ige_2 = c(0,1,2,3),
                 ige_3 = c(0,1,2,3),
                 ige_1_copy = c(1,2,3,4),
                 ige_2_copy = c(1,2,3,4),
                 ige_3_copy = rep(c(1,2,3,4),100))

copy 表示该变量是另一天测量的。我的兴趣是专门在这些变量之间执行相关性。因此,我可以这样做:

cor(ds$ige_1, ds$ige_1_copy)
cor(ds$ige_2, ds$ige_2_copy)
cor(ds$ige_3, ds$ige_3_copy)

然而,我想让这更容易,但我的循环不工作。

for (i in 1:4) {
  cor(ds$ige_[[i]], ds_ige_[[i]]_copy, use = "complete.obs")
}

有什么建议吗? R base 或 R tidyverse 将不胜感激。

完整代码

ds <- data.frame(ige_1 = c(0,1,2,3),
                 ige_2 = c(0,1,2,3),
                 ige_3 = c(0,1,2,3),
                 ige_1_copy = c(1,2,3,4),
                 ige_2_copy = c(1,2,3,4),
                 ige_3_copy = rep(c(1,2,3,4),100))

cor(ds$ige_1, ds$ige_1_copy)
cor(ds$ige_2, ds$ige_2_copy)

for (i in 1:4) {
  cor(ds$ige_[[i]], ds_ige_[[i]]_copy, use = "complete.obs")
}

也许这就是你想要的?

ds <- data.frame(ige_1 = c(0,1,2,3),
             ige_2 = c(0,1,2,3),
             ige_3 = c(0,1,2,3),
             ige_1_copy = c(1,2,3,4),
             ige_2_copy = c(1,2,3,4),
             ige_3_copy = rep(c(1,2,3,4),100))

cor_var <- numeric()
for (i in 1:3) {
    cor_var[i] <- cor(ds[[paste("ige",i, sep = "_")]],
                      ds[[paste("ige",i,"copy", sep = "_")]], 
                      use = "complete.obs")
}

cor_var

您也可以在 for 循环中使用“print”,而不是将其存储在变量中。

您也可以只执行 cor(ds) 以获得所有组合:

ds <- data.frame(ige_1 = c(0,1,2,3),
                 ige_2 = c(0,1,2,3),
                 ige_3 = c(0,1,2,3),
                 ige_1_copy = c(1,2,3,4),
                 ige_2_copy = c(1,2,3,4),
                 ige_3_copy = rep(c(1,2,3,4),100))



cor(ds)

结果:

           ige_1 ige_2 ige_3 ige_1_copy ige_2_copy ige_3_copy
ige_1          1     1     1          1          1          1
ige_2          1     1     1          1          1          1
ige_3          1     1     1          1          1          1
ige_1_copy     1     1     1          1          1          1
ige_2_copy     1     1     1          1          1          1
ige_3_copy     1     1     1          1          1          1