我有以下数据:
library(dplyr)
library(purrr)
d <- data.frame(
Type= c("d", "e", "d", "e"),
"2000"= c(1, 5, 1, 5),
"2001" = c(2, 5 , 6, 4),
"2002" = c(8, 9, 6, 3))
我想使用rowsum和mutate生成一个新行,它是“ d”的总和,而另一行是“ e”的总和,因此数据看起来像这样:
d2 <- data.frame(
Type= c("d", "e", "d", "e", "sum_of_d", "Sum_of_e"),
"2000"= c(1, 5, 1, 5, 2, 10),
"2001" = c(2, 5 , 6, 4, 8, 9),
"2002" = c(8, 9, 6, 3, 14, 12))
我认为代码应如下所示:
d %>%
dplyr::mutate(sum_of_d = rowSums(d[1,3], na.rm = TRUE)) %>%
dplyr::mutate(sum_of_e = rowSums(d[2,4], na.rm = TRUE)) -> d2
但是,这不太有效。有任何想法吗?
谢谢
答案 0 :(得分:4)
您要在所有其他列中按类型查找总和,所以
library(dplyr)
d %>%
group_by(Type) %>%
summarise_all(sum) %>%
mutate(Type = paste0("sum_of_", Type)) %>%
rbind(d, .)
Type X2000 X2001 X2002
1 d 1 2 8
2 e 5 5 9
3 d 1 6 6
4 e 5 4 3
5 sum_of_d 2 8 14
6 sum_of_e 10 9 12
答案 1 :(得分:0)
d %>%
group_by(Type) %>%
summarize_all(sum) %>%
mutate(Type=paste0("sum_of_",Type)) %>%
bind_rows(d,.)
Type X2000 X2001 X2002
1 d 1 2 8
2 e 5 5 9
3 d 1 6 6
4 e 5 4 3
5 sum_of_d 2 8 14
6 sum_of_e 10 9 12