R-将列子集内多个组中的变量与另一列中的第二个组求和



我一直在寻找我的问题的例子,但一直找不到

plot_id <- c("plot_1","plot_1","plot_1","plot_1","plot_2","plot_2","plot_2","plot_2")
size_class <- c("1","2","3","4","1","2","3","4")
weight <- c(1.05,11.06,17.48,131.76,0.23, 8.38, 3.30,69.58)
df <- data.frame(plot_id,size_class,weight)
plot_id size_class weight
1  plot_1          1   1.05
2  plot_1          2  11.06
3  plot_1          3  17.48
4  plot_1          4 131.76
5  plot_2          1   0.23
6  plot_2          2   8.38
7  plot_2          3   3.30
8  plot_2          4  69.58

我想对由plot_id分组的size_class1、2和3上的weight求和。所得到的总和将是新的size_class123。所以结果看起来是这样的:

plot_id size_class weight
1  plot_1        123  29.59
2  plot_2        123  11.91

然后我想将这些新的观察添加到原始数据帧中。

我仍在掌握数据争论,但我还没能弄清楚这一点,非常感谢任何帮助!

您可以使用

library(dplyr)
df %>% 
filter(size_class %in% 1:3) %>% 
group_by(plot_id) %>% 
summarise(size_class = paste0(size_class, collapse = ""),
weight = sum(weight)) %>% 
bind_rows(df)

这将返回

# A tibble: 10 x 3
plot_id size_class weight
<chr>   <chr>       <dbl>
1 plot_1  123         29.6 
2 plot_2  123         11.9 
3 plot_1  1            1.05
4 plot_1  2           11.1 
5 plot_1  3           17.5 
6 plot_1  4          132.  
7 plot_2  1            0.23
8 plot_2  2            8.38
9 plot_2  3            3.3 
10 plot_2  4           69.6 

最新更新