从多行组合中添加新行

add new rows from combination of multiple rows

我正在尝试将各种列添加到一起,以便在满足条件的情况下将新行添加到数据框 df 的末尾。

SurveyYear State Stratum Plot species pairs males_24 tib
1       2015    CT      12    4    MALL     0        0   1
2       2015    CT      12    4    ABDU     1        2   4
3       2015    CT      12    4    AGWT     1        0   0
4       2015    CT      11    2    ABDU     2        1   2
5       2015    CT      11    2    MALL     0        1   0
6       2015    CT      11    2    ABDU     4        4   7

对于每个分组的 State、Stratum 和 Plot,我想向 df 添加一行,其中包含对、males_24 和 tib 的总和。这需要由物种组来完成,才能形成一个新物种 "TODU"。在这种情况下,将所有物种加起来 = ABDU 和 AGWT(实际数据集有大约 8 个物种要加起来,4 个不包括)。所以会有 2 个新行(保持所有其他行不变)添加到 df 是:

2015 CT 12 4 TODU 2 2 4
2015 CT 11 2 TODU 6 5 9

我可以很容易地手动添加行,或者使用

添加单个列
df[nrow(df) + 1, ] <- c(,)

但我很难弄清楚如何分组和求和,同时保持数据集的其余部分完好无损,并针对许多变化执行此操作。在 SAS 中,我会使用 proc sort 执行此操作,但我认为我不需要先使用 R 进行排序。任何帮助将不胜感激。谢谢

dplyr 你可以做到(数据是 dat

library(dplyr)

new_rows <- dat %>% group_by(State, Stratum, Plot) %>%
  summarise(SurveyYear = 2015,
            species = "TODU",
            pairs = sum(pairs),
            males_24 = sum(males_24),
            tib = sum(tib))
new_rows
#   State Stratum Plot SurveyYear species pairs males_24 tib
# 1    CT      11    2       2015    TODU     6        6   9
# 2    CT      12    4       2015    TODU     2        2   5

rbind(dat, new_rows)

编辑:对一些物种求和,先总结,然后添加物种列。

specs <- c("AGWT", "ABDU")
new_rows <- dat %>% group_by(State, Stratum, Plot) %>%
  summarise(SurveyYear = 2015,
            pairs = sum(pairs[species %in% specs]),
            males_24 = sum(males_24[species %in% specs]),
            tib = sum(tib[species %in% specs])) %>%
  mutate(species = "TODU")
new_rows

#   State Stratum Plot SurveyYear pairs males_24 tib species
# 1    CT      11    2       2015     6        5   9    TODU
# 2    CT      12    4       2015     2        2   4    TODU