Table 的平均值 (SD)

Table of mean (SD)s

我有一个相对较大的数据集,我想打印 table 因子组合的均值和标准差。我希望它们采用这样的格式:

         A            B
test1    2.0 (1.0)    5.0 (2.0)
test2    6.3 (3.1)    2.1 (0.7)

有没有简单的方法来做到这一点?

我得到的最接近的是使用 tables::tabular 函数(最小示例):

# Example data
df = data.frame(
   group=c('A', 'A',  'A', 'B', 'B', 'B'),
   value=c(1,2,3,6,8,9))

# Print table     
library(tables)
tabular(value ~ group * (mean + sd), df)

...输出这个:

       group               
       A        B          
       mean  sd mean  sd   
 value 2     1  7.667 1.52

但我还没有想出一个巧妙的方法来将这种格式转换为上面的 mean (SD) 格式。注意:这些示例非常少。我将有一个更大的层次结构(目前 4 x (mean+sd) 列和 2 x 3 行)但基本问题是相同的。

从data.table开始,我们可以使用dcast(包括你的测试变量):

library(data.table)

df = data.frame(
  group=c('A', 'A',  'A', 'B', 'B', 'B','A', 'A',  'A', 'B', 'B', 'B'),
  value=c(1,2,3,6,8,9,1,2,3,6,8,9),
  test=c(1,1,1,1,1,1,2,2,2,2,2,2))

dcast(df, test ~ group, fun.aggregate = function(x){
  paste(round(mean(x),1)," (", round(sd(x),1),")", sep = "")
})
  test     A         B
1    1 2 (1) 7.7 (1.5)
2    2 2 (1) 7.7 (1.5)
library(reshape2)

formatted.table <- dcast(df, 'value' ~ group, fun.aggregate = function(x) {
    return(sprintf('%0.1f (%0.1f)', mean(x), sd(x)))
})

# "value"         A         B
#   value 2.0 (1.0) 7.7 (1.5)

与 Chris 的回答类似,但更简洁(并且不需要 "test" 变量)。

您也可以使用 dplyr 包进行此类聚合。