在 R 中编写一个 for-loop,用相关测试的输出(估计和置信区间)填充矩阵?

Writing a for-loop in R that populates a matrix with the output of a correlation test (estimates and confidence intervals)?

正如标题所暗示的,我想在 R 中编写一个 for-loop,它将一个变量作为给定的 (a),创建第二个变量的 10 种不同排列 (b),计算相关性测试并将输出(相关估计和置信区间)存储在数据框或矩阵中。该矩阵因此应包含三列(估计值、较低值、较高值)和 10 行。

之后,我想绘制输出,使用 ggplot 将每个相关性测试显示为 geom_point() + geom_linerange(lower, upper) 参考线位于 yintercept=0

a <- 1:100
b <- c(rep(0,100))
data <- matrix(ncol = 3, nrow = 10)

for (i in 1:10) {
  b[i] <- sample(100, replace = FALSE)
  temp <- cor.test(a,b)
  correlation <- as.numeric(temp$estimate)
  lower <- as.numeric(temp$conf.int[1])
  upper <- as.numeric(temp$conf.int[2])
  data[i,] <- c(correlation[i], lower[i], upper[i])
  print(data)
  #ggplot(data, aes(x=paste0("correlation_",[i]), y=correlation)) + 
     #geom_point(color="red") + 
     #geom_linerange(ymin=lower, ymax=upper, color="red") + 
     #geom_hline(yintercept = 0, linetype="dashed")
}

出于某种原因,这不起作用。我猜这与我尝试将相关测试结果的输出存储在 data 中的方式有​​关。 for-loop,就像现在一样,创建了 10 个矩阵,第一个包含所有输出,然后从第二个开始逐渐下降一行,直到除第一个之外的所有矩阵都是 NA。另外,我不确定 ggplot() 调用是否会像现在这样工作。

有人可以帮忙吗?

首先,b[i] 不起作用,因为 b 是一个数值向量,您尝试将另一个向量(长度为 100)分配给 i-th b 的元素。您也不需要事先初始化 b。循环中只需 b <- sample(1:100, replace = FALSE) 就足够了。

其次,c(correlation[i], lower[i], upper[i]) 尝试访问 correlationupper 和 [=] 的 i-th 值27=]降低。这不起作用(超过 i = 1),因为每个只包含一个值,您在循环的每次迭代中重新分配该值。

这个有效:

a <- 1:100
data <- matrix(ncol = 3, nrow = 10)

for (i in 1:10) {
  b <- sample(1:100, replace = FALSE)
  temp <- cor.test(a,b)
  correlation <- as.numeric(temp$estimate)
  lower <- as.numeric(temp$conf.int[1])
  upper <- as.numeric(temp$conf.int[2])
  data[i,] <- cbind(correlation, lower, upper)
}

稍微简单一点的版本(使用循环时)是将值直接分配给 data,而不是先在循环中将它们存储在对象中。

a <- 1:100
data <- matrix(ncol = 3, nrow = 10,
               dimnames = list(NULL, c("correlation", "lower", "upper")))

for (i in 1:10) {
  b <- sample(1:100, replace = FALSE)
  temp <- cor.test(a,b)
  data[i,"correlation"] <- as.numeric(temp$estimate)
  data[i,"lower"] <- as.numeric(temp$conf.int[1])
  data[i,"upper"] <- as.numeric(temp$conf.int[2])
}

编辑: 关于ggplot-code:如果将数据转换为data.frame并添加id-variable(如果您想要x-axis 和 text-labels)。 ymin 和 ymax 也必须定义为 geom_linerange().

的美学
library(ggplot2)
data <- as.data.frame(data)
data$id <- paste0("cor_", 1:10)

ggplot(data, aes(x=id, y=correlation)) +
  geom_point(color="red") +
  geom_linerange(aes(ymin=lower, ymax=upper), color="red") +
  geom_hline(yintercept = 0, linetype="dashed")