【问题标题】:Calculate summary data with R用 R 计算汇总数据
【发布时间】:2013-02-10 14:56:52
【问题描述】:

我的数据框如下所示:

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 对的一些汇总值。我使用以下方法计算了平均值和标准差:

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")

但我想将比较 A 与 B 的 t.test 中的 p 值添加到 summary.table 中。到目前为止,我已经这样做了,但这不仅没有写入 summary.table,而且我不能获取要打印的 factor2 变量的名称:

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

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

【问题讨论】:

    标签: r casting summary


    【解决方案1】:

    我会这样做:

    首先,使用ddplyplyr 使用summarise 获取meansd 摘要

    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
    

    然后,为t-test 获取p-valuesmean(A) = mean(B)XY 级别在factor2 中的factor2

    o2 <- ddply(df, .(factor2), summarise, pval=t.test(value ~ factor1)$p.value)
    
    #   factor2      pval
    # 1       X 0.8108754
    # 2       Y 0.5614256
    

    然后,使用reshape2meltdcasto1 转换为所需的格式。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      相关资源
      最近更新 更多