首页 > 解决方案 > `$<-.data.frame`(`*tmp*`, conf.int, value = list(X1 = c(-0.305562185432494, : 替换有 2 行,数据有 20

问题描述

我想在数据框中添加 t.test 函数 conf.int 的输出,使用下面的代码

y <- data.frame(matrix(rnorm(1000),20))
test <- apply(y, 1, t.test, alternative = c("two.sided", "less", "greater"),mu = 0, paired = FALSE, var.equal = FALSE,conf.level = 0.95)
y$conf.int <-data.frame(sapply(test,function(x)c(x$conf.int)))

然而它返回

Error in `$<-.data.frame`(`*tmp*`, w, value = list(X1 = c(-0.305562185432494,  : replacement has 2 rows, data has 20

我搜索了解决方案,然后修改了下面给出的代码

y$x1_range <- NA
y$x1_range[which(y$x1 <= 2)] <-data.frame(sapply(test,function(x)c(x$conf.int)))

但它只创建空列,没有别的。

提前致谢

标签: r

解决方案


您可以从中提取'conf.int'test获取 2 列矩阵和cbind原始y.

y <- data.frame(matrix(rnorm(1000),20))

test <- apply(y, 1, t.test, alternative = c("two.sided", "less", "greater"),
              mu = 0, paired = FALSE, var.equal = FALSE,conf.level = 0.95)

result <- cbind(y, t(sapply(test, `[[`, 'conf.int')))

推荐阅读