Search code examples
rlistdataframedplyrsummarize

Arithmetic on summarized dataframe from dplyr in R


I have a large dataset I use dplyr() summarize to generate some means. Occasionally, I would like to perform arithmetic on that output. For example, I would like to get the mean of means from the output below, say "m.biomass".

I've tried this mean(data.sum[,7]) and this mean(as.list(data.sum[,7])). Is there a quick and easy way to achieve this?

data.sum <-structure(list(scenario = c("future", "future", "future", "future"
), state = c("fl", "ga", "ok", "va"), m.soc = c(4090.31654013689, 
3654.45350562628, 2564.33199749487, 4193.83388887064), m.npp = c(1032.244475, 
821.319385, 753.401315, 636.885535), sd.soc = c(56.0344229400332, 
97.8553643582118, 68.2248389927858, 79.0739969429246), sd.npp = c(34.9421782033153, 
27.6443555578531, 26.0728757486901, 24.0375040705595), m.biomass = c(5322.76631158111, 
3936.79457763176, 3591.0902359206, 2888.25308402464), sd.m.biomass = c(3026.59250918009, 
2799.40317348016, 2515.10516340438, 2273.45510178843), max.biomass = c(9592.9303, 
8105.109, 7272.4896, 6439.2259), time = c("1980-1999", "1980-1999", 
"1980-1999", "1980-1999")), .Names = c("scenario", "state", "m.soc", 
"m.npp", "sd.soc", "sd.npp", "m.biomass", "sd.m.biomass", "max.biomass", 
"time"), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -4), vars = list(quote(scenario)), labels = structure(list(
    scenario = "future"), class = "data.frame", row.names = c(NA, 
-1), vars = list(quote(scenario)), drop = TRUE, .Names = "scenario"), indices = list(0:3))

Solution

  • We can use [[ to extract the column as a vector; as mean only works on a vector or a matrix -- not on a data.frame. If the OP wanted to do this on a single column, use this:

    mean(data.sum[[7]]) 
    #[1] 3934.726
    

    If there was only the data.frame class, the data.sum[,7] would be extracting it as a vector, but the tbl_df prevents it to collapse it to vector


    For multiple columns, the dplyr also has specialised functions

    data.sum %>%
           summarise_each(funs(mean), 3:7)