r - Table of mean (SD)s -


i have relatively large dataset, , want print table of means , standard deviations combinations of factors. have them in format this:

                    b test1    2.0 (1.0)    5.0 (2.0) test2    6.3 (3.1)    2.1 (0.7) 

is there easy way this?

the closest using tables::tabular function (minimal example):

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

... outputs this:

       group                              b                  mean  sd mean  sd     value 2     1  7.667 1.52 

but haven't figured out neat way transform format mean (sd) format above. note: these examples minimal. have larger hierarchy (currently 4 x (mean+sd) columns , 2 x 3 rows) fundamental problem same.

library(reshape2)  formatted.table <- dcast(df, 'value' ~ group, fun.aggregate = function(x) {     return(sprintf('%0.1f (%0.1f)', mean(x), sd(x))) })  # "value"                 b #   value 2.0 (1.0) 7.7 (1.5) 

similar chris's answer, little bit cleaner (and no "test" variable needed).

you can type of aggregation dplyr package.


Comments