【问题标题】:Summarize data by 2 groups按 2 组汇总数据
【发布时间】:2015-10-23 04:23:22
【问题描述】:

我想按两个类为我的数据生成描述性统计数据:1) “SampledSub”和“SampledLUL”在此处使用我的数据子集:

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

我用这段代码按 2 组进行了总结:

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

但输出表同时包含组和汇总统计信息作为列。如何生成类似于下图的表格?就我而言,“Sampledsub”将是观察结果,汇总统计数据将根据“SampledLUL”进行分组。

【问题讨论】:

  • 你可以从library(tables)查看?tabular
  • @akrun 该软件包不适用于 R 3.2.0+ 从我尝试过的。
  • @PierreLafortune 我没试过。
  • 这次dput 做得很好!

标签: r plyr


【解决方案1】:

你可以用tidyr 来做(虽然它不会像上面那样是一个很好的输出表):

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

【讨论】:

  • 太棒了,我在 excel 中清理它以进行演示。
猜你喜欢
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多