用R计算摘要数据

时间:2013-02-10 14:56:53

标签: r casting summary

我的数据框看起来像这样:

set.seed(123)
df <- data.frame(factor1 = rep(c("A", "B"),50),
                 factor2 = rep(c("X","X", "Y", "Y"),25),
                 value = rnorm(100))

我想计算factor1:factor2对的一些汇总值。我使用以下方法计算了均值和sd:

summary <- as.matrix(cast(df, factor1~factor2, mean))
summary.sd <- as.matrix(cast(df, factor1~factor2, sd))
summary.table <- t(rbind(summary, summary.sd))
colnames(summary.table) <- c("A.mean", "B.mean", "A.sd", "B.sd")

但是我想在summary.table中添加t.test中的p值来比较A和B.到目前为止我已经完成了这个,但这不仅不写到summary.table但我不能获取要打印出来的factor2变量的名称:

for (measurement in levels(df$factor2)) print(t.test(value~factor1, data=subset(df, factor2==measurement)))

我认为必须有一些简单的方法来做到这一点,或者一个我不知道的包会使这更直接。

1 个答案:

答案 0 :(得分:3)

我这样做:

首先,使用mean sd使用ddply获取plyrsummarise摘要

require(plyr)
require(reshape2)
o1 <- ddply(df, .(factor1, factor2), summarise, mean = mean(value), sd=sd(value))

#   factor1 factor2       mean        sd
# 1       A       X 0.03746854 0.8730525
# 2       A       Y 0.18352432 0.7635439
# 3       B       X 0.10317706 1.0494930
# 4       B       Y 0.03745372 0.9876173

然后,对p-values中的t-testmean(A) = mean(B)级别的X Y factor2获取o2 <- ddply(df, .(factor2), summarise, pval=t.test(value ~ factor1)$p.value) # factor2 pval # 1 X 0.8108754 # 2 Y 0.5614256

reshape2

然后,使用melt的{​​{1}}和dcast投射o1到所需的格式。

o1.mc <- dcast(melt(o1, c("factor1", "factor2")), factor2 ~ variable + factor1)

#   factor2     mean_A     mean_B      sd_A      sd_B
# 1       X 0.03746854 0.10317706 0.8730525 1.0494930
# 2       Y 0.18352432 0.03745372 0.7635439 0.9876173

现在,将其与o2合并:

merge(o1.mc, o2)

#   factor2     mean_A     mean_B      sd_A      sd_B      pval
# 1       X 0.03746854 0.10317706 0.8730525 1.0494930 0.8108754
# 2       Y 0.18352432 0.03745372 0.7635439 0.9876173 0.5614256