简体   繁体   中英

Summarize data by 2 groups

I'd like to generate descriptive statistics for my data by two classes : 1) "SampledSub" and "SampledLUL" using a subset of my data here:

myData <- structure(list(SampledLUL = structure(c(12L, 12L, 9L, 9L, 9L, 
9L), .Label = c("citrus", "crop", "cypress swamp", "freshwater marsh and wet prairie", 
"hardwood swamp", "improved pasture", "mesic upland forest", "mixed wetland forest", 
"pineland", "rangeland", "shrub swamp", "urban", "xeric upland forest"), class = "factor"), 
SampledSub = structure(c(12L, 12L, 4L, 12L, 8L, 4L), .Label = c("Aqualf", "Aquent", 
"Aquept", "Aquod", "Aquoll", "Aquult", "Arent", "Orthod", "Psamment", "Saprist", "Udalf", 
"Udult"), class = "factor"), SOC = c(3.381524292, 6.345916406, 2.122765119, 2.188488973, 
6.980834272, 7.363643479)), 
.Names = c("SampledLUL", "SampledSub", "SOC"), row.names = c(NA, 6L), class = "data.frame")

I've used this code to summarize by 2 groups:

group.test <- ddply(buffer, c("SampledSub", "SampledLUL"), summarise,
                   N    = length(SOC),
                   mean = mean(SOC),
                   sd   = sd(SOC),
                   se   = sd / sqrt(N) )

But the output table has both groups and summary stats as columns. How can I produce a table similar to the one shown below? In my case, "Sampledsub" would be the observations, and summary statistics would be grouped according to "SampledLUL".

在此输入图像描述

You can do it with tidyr (though it won't be a nice output table like the above):

library(tidyr)
group.test %>% gather(variable, val, - SampledSub, -SampledLUL) %>%
               unite(newcol, SampledLUL, variable) %>%
               spread(newcol, val)

  SampledSub pineland_mean pineland_N pineland_sd pineland_se urban_mean urban_N urban_sd urban_se
1      Aquod      4.743204          2    3.705861    2.620439         NA      NA       NA       NA
2     Orthod      6.980834          1         NaN         NaN         NA      NA       NA       NA
3      Udult      2.188489          1         NaN         NaN    4.86372       2 2.096142 1.482196

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM