首页 > 解决方案 > 是否可以在 group_by() 之后执行多个汇总函数?

问题描述

我一直在努力解决这个问题很长时间,但我越来越绝望。

我有一个数据集 (B2),其中包含在 5 个不同位置确定的 25 个海草叶片中某些特征的计数数据。例如,如果刀片有 F1 咬合,则算作 +1。为了获得我需要的堆叠条形图,我必须以精确的方式生成数据框/小标题。我已经成功地编写了一个代码来一次获得一个特征的小标题。即:

> B2 %>%
+   group_by(Location) %>%
+   summarise(Present = c("Yes","No"),
+             value = ifelse(Present == "Yes", sum(Bite_F1), 25-sum(Bite_F1)),
+             Type = "Big bite")
`summarise()` has grouped output by 'Location'. You can override using the `.groups` argument.
# A tibble: 10 x 4
# Groups:   Location [5]
   Location Present value Type    
   <fct>    <chr>   <dbl> <chr>   
 1 Nizuc    Yes         1 Big bite
 2 Nizuc    No         24 Big bite
 3 Ceiba    Yes         1 Big bite
 4 Ceiba    No         24 Big bite
 5 Tortuga  Yes         2 Big bite
 6 Tortuga  No         23 Big bite
 7 Caricomp Yes        14 Big bite
 8 Caricomp No         11 Big bite
 9 Lagoon   Yes         0 Big bite
10 Lagoon   No         25 Big bite

> B2 %>%
+   group_by(Location) %>%
+   summarise(Present = c("Yes","No"),
+             value = ifelse(Present == "Yes", sum(Bite_F2), 25-sum(Bite_F2)),
+             Type = "Small bite")
`summarise()` has grouped output by 'Location'. You can override using the `.groups` argument.
# A tibble: 10 x 4
# Groups:   Location [5]
   Location Present value Type      
   <fct>    <chr>   <dbl> <chr>     
 1 Nizuc    Yes        23 Small bite
 2 Nizuc    No          2 Small bite
 3 Ceiba    Yes        14 Small bite
 4 Ceiba    No         11 Small bite
 5 Tortuga  Yes        23 Small bite
 6 Tortuga  No          2 Small bite
 7 Caricomp Yes         8 Small bite
 8 Caricomp No         17 Small bite
 9 Lagoon   Yes        11 Small bite
10 Lagoon   No         14 Small bite

当然,我可以为所有 6 个特征制作一个单独的数据帧/小标题,最后将这 6 个数据帧/小标题加在一起,但这似乎有点多余。我无法想象没有办法一次完成所有操作,但我似乎无法弄清楚如何。有人有任何提示或建议吗?

标签: group-bysummarize

解决方案


推荐阅读