使用聚集在R中已经聚集的data.frame上

时间:2016-10-05 11:44:46

标签: r dplyr tidyr

我在R中有一个data.frame,它包含年龄,长度和每个长度组中个人的总数。我想得到每个年龄组的长度的均值和标准差,我觉得用dplyr这样做最容易。但是,我似乎无法弄清楚如何gather()这个特定的数据集。这是数据:

dat <- data.frame(age = sort(rep(1:5, 5)),
              length = c(6:10, 8:12, 10:14, 12:16, 14:18),
              total = sample(25:50, 50, replace=T))

看起来像这样:

  age length total
   1      6    38
   1      7    42
   1      8    49
   1      9    28
   1     10    26
   2      8    37

并且,我希望它看起来如下所示,以便我可以轻松group_by(age) %>% summarize(mean = mean(length), sd = sd(length))

age  length
1     6
1     6
1     6
1     6
1     6

等。 (即1岁时应该有38 6s,1岁时应该有42 7s等等。)

如何使用tidyr的gather()功能实现此目的?我似乎无法做到这一点。很高兴听到其他建议。

1 个答案:

答案 0 :(得分:1)

如何计算加权平均值?

guard let item = SLComposeSheetConfigurationItem() else { return nil }

编辑:在我之前发布R之后有一个dat <- data.frame(age = sort(rep(1:5, 5)), length = c(6:10, 8:12, 10:14, 12:16, 14:18), total = sample(25:50, 50, replace=T)) library(magrittr) library(dplyr) dat %>% group_by(age) %>% summarise(mean_length = sum(length * total) / sum(total), wtd_mean = weighted.mean(length, total)) 函数让我更简单的事情发生了。