r-如何对分组数据帧执行操作



我有以下数据帧morphology:

month site  depth num.core num.plant num.leaf
<chr> <chr> <dbl>    <dbl>     <dbl>    <dbl>
1 Oct   SB       12        1         1        5
2 Oct   SB       12        1         2       29
3 Oct   SB       12        1         3        7
4 Oct   SB       12        2         1        9
5 Oct   SB       12        2         2        4
6 Oct   SB       12        2         3       13

我的目标是计数设定日期(month(和depth的每个核心(num.core(的植物数量(num.plant(。

我已经对数据帧进行了分组,并根据需要计算了每个核心的工厂数量:

morpho.group <- morphology %>%
group_by(month, site, num.core, depth) %>%
count(month,site,num.core,depth, name = "plant.count.Xcore") 
month site   num.core depth plant.count.Xcore
<chr> <chr>     <dbl> <dbl>             <int>
1 Dec   D           1     3                 4
2 Dec   D           2     3                 2
3 Dec   D           3     3                 3
4 Dec   D           4     3                 3
5 Dec   N           1    12                 1
6 Dec   N           2    12                 5

我的问题是我需要对morphology数据帧执行更多操作,例如对每个核心的叶数求和,例如:

count.morpho <- morphology %>%
group_by(month, site, num.core, depth) %>%
summarise_at(vars("num.leaf", "num.roots"), sum)
month site   num.core depth num.leaf num.roots
<chr> <chr>     <dbl> <dbl>    <dbl>     <dbl>
1 Dec   D           1     3       11        13
2 Dec   D           2     3       17         8
3 Dec   D           3     3       14         4
4 Dec   D           4     3       40        10
5 Dec   N           1    12        3         2
6 Dec   N           2    12       40        10

我需要执行这些操作,使它们继续并添加到单个数据帧中,而不是将每个计算列拉到一个新的数据帧中。

非常感谢您的帮助:(

count实际上只是一个查看组的n()的方便函数,您可以更确切地包含它并添加其他度量。

(仅供参考,您的数据不包括num.roots,所以我在这里用num.plant代替它只是为了演示。(

morphology %>%
group_by(month, site, num.core, depth) %>%
summarize(
plant.count.Xcore = n(), 
across(c(num.leaf, num.plant), sum)
) %>%
ungroup()
# # A tibble: 2 x 7
#   month site  num.core depth plant.count.Xcore num.leaf num.plant
#   <chr> <chr>    <int> <int>             <int>    <int>     <int>
# 1 Oct   SB           1    12                 3       41         6
# 2 Oct   SB           2    12                 3       26         6

仅供参考,CCD_;被取代的";通过CCD_ 12。请注意,现在发生了变化:像往常一样使用summarize,使用across但不分配给某个东西,本身;第一个要跨越的arg是一组要选择的变量,使用与select类似的方法,包括c(col1, col2)starts_with("num")和这些选项的否定;第二个自变量是一个或多个不同方式的函数,类似于summarize_at的函数自变量。有关更多详细信息,请参阅colwise小插曲。

最新更新