0

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

之后,我想绘制输出,使用 ggplot 将每个相关测试显示为 a 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 循环创建了 10 个矩阵,其中第一个矩阵包含所有输出,然后从第二个开始逐渐下降一行,直到除第一个之外的所有矩阵都是NA. 另外,我不确定这个ggplot()电话会像现在这样工作。

有人可以帮忙吗?

4

1 回答 1

3

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

其次,c(correlation[i], lower[i], upper[i])尝试访问相关性的第 i 个值。这不起作用(超出 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 代码:如果将数据转换为 data.frame 并添加 id 变量(如果您想要 x 轴上带有文本标签的数据行),则更容易。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")
于 2020-11-04T13:28:16.773 回答