Summing data for 2 groups

I would like to generate descriptive statistics for my data in 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 used this code to sum over two 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 statistics as columns. How can I create a table similar to the one below? In my case, "Sampledsub" will be an observation, and summary statistics will be grouped according to "SampledLUL".

enter image description here

+4
source share
1 answer

You can do this with tidyr(although this will not be a good output table, as mentioned 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
+1
source

Source: https://habr.com/ru/post/1612826/


All Articles