繁体   English   中英

cor.test到R中的data.frame

[英]cor.test into data.frame in R

考虑以下示例:

require(MuMIn)
data(Cement)
d <- data.frame(Cement)

idx <- seq(11,13)
cor1 <- list()
for (i in 1:length(idx)){
  d2 <- d[1:idx[i],]
  cor1[[i]] <- cor.test(d2$X1,d2$X2, method = "pearson")
}
out <- lapply(cor1, function(x) c(x$estimate, x$conf.int, x$p.value))

在这里,我计算迭代循环中数据集的相关性。

我知道想生成一个data.frame,由列表'out'中的值组成。 我尝试使用

df <- do.call(rbind.data.frame, out)

但结果似乎不对:

> df
  c.0.129614123011664..0.195326511912326..0.228579470307565.
1                                                  0.1296141
2                                                  0.1953265
3                                                  0.2285795
  c..0.509907346173941...0.426370467476045...0.368861726657293.
1                                                    -0.5099073
2                                                    -0.4263705
3                                                    -0.3688617
  c.0.676861607564929..0.691690831088494..0.692365536706126.
1                                                  0.6768616
2                                                  0.6916908
3                                                  0.6923655
  c.0.704071702633775..0.542941653020805..0.452566184329491.
1                                                  0.7040717
2                                                  0.5429417
3                                                  0.4525662

这不是我追求的。

如何生成一个data.frame,其第一列表示cor.test的计算列表,在这种情况下为1到3,第二列是指$ estimate,然后是$ conf.int和%p.value得到的在五列data.frame中。

这是你想要做的吗? 你的问题有点难以理解。 列表中的一列索引真的有必要吗? 整个第一列与行名称(显示在左侧)完全相同。

> D <- data.frame(cbind(index = seq(length(out)), do.call(rbind, out)))
> names(D)[2:ncol(D)] <- c('estimate', paste0('conf.int', 1:2), 'p.value')
> D
  index  estimate  conf.int1 conf.int2   p.value
1     1 0.1296141 -0.5099073 0.6768616 0.7040717
2     2 0.1953265 -0.4263705 0.6916908 0.5429417
3     3 0.2285795 -0.3688617 0.6923655 0.4525662

你要问的是什么并不完全清楚......你有这样一个数据框,只是没有合理的列名。 您可以将代码简化为..

ctests <- lapply(idx, function(x) cor.test(d[1:x,"X1"], d[1:x, "X2"]))
ctests <- lapply(ctests, "[", c("estimate", "conf.int", "p.value"))
as.data.frame(do.call(rbind, lapply(ctests, unlist)))
#   estimate.cor  conf.int1 conf.int2   p.value
# 1    0.1296141 -0.5099073 0.6768616 0.7040717
# 2    0.1953265 -0.4263705 0.6916908 0.5429417
# 3    0.2285795 -0.3688617 0.6923655 0.4525662

这是你需要的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM