我有一个与群组相关联的个人值的数据框。我想确定那些平均值大于平均值的组加上整个数据集的一个标准偏差。为此,我计算整个数据框的平均值和标准差,然后运行成对t检验以与每个组平均值进行比较。我输出结果时遇到了麻烦。
> head(df)
individual group value
1 11559638 75 0.371
2 11559641 75 0.367
3 11559648 75 0.410
4 11559650 75 0.417
5 11559652 75 0.440
6 11559654 75 0.395
> allvalues <- data.frame(mean=rep(mean(df$value), length(df$individual)), sd=rep(sd(df$value), length(df$individual)))
> valueplus <- with(df, by(df, df$individual, function(x) t.test(allvalues$mean + allvalues$sd, df$value, data=x)))
> tmpplus
--------------------------------------------------------------------------
df$individuals: 10
NULL
--------------------------------------------------------------------------
df$individuals: 20
NULL
--------------------------------------------------------------------------
df$individuals: 21
Welch Two Sample t-test
data: allvalues$mean + allvalues$sd and df$value
t = 84.5217, df = 4999, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
0.04676957 0.04899068
sample estimates:
mean of x mean of y
0.4719964 0.4241162
如何将结果导入数据框?我希望输出看起来像这样:
groups t df p-value mean.x mean.y
1 10 NULL NULL NULL NULL NULL
2 20 NULL NULL NULL NULL NULL
3 21 84.5217 4999 2.2e-16 0.4719964 0.4241162
答案 0 :(得分:4)
从纯粹的编程角度来看,您正在询问如何将t.test
的输出转换为data.frame
。请使用mtcars
library(broom)
tidy(t.test(mtcars$mpg))
estimate statistic p.value parameter conf.low conf.high
1 20.09062 18.85693 1.526151e-18 31 17.91768 22.26357
或多组:
library(dplyr)
mtcars %>% group_by(carb) %>% do(tidy(t.test(mtcars$mpg)))
Source: local data frame [6 x 7]
Groups: carb [6]
carb estimate statistic p.value parameter conf.low conf.high
(dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl)
1 1 20.09062 18.85693 1.526151e-18 31 17.91768 22.26357
2 2 20.09062 18.85693 1.526151e-18 31 17.91768 22.26357
3 3 20.09062 18.85693 1.526151e-18 31 17.91768 22.26357
4 4 20.09062 18.85693 1.526151e-18 31 17.91768 22.26357
5 6 20.09062 18.85693 1.526151e-18 31 17.91768 22.26357
6 8 20.09062 18.85693 1.526151e-18 31 17.91768 22.26357
毋庸置疑,您需要调整代码以适合您的具体设置。