首页 > 解决方案 > dplyr:根据匹配的行添加数字

问题描述

假设我有

> fig
  hands imp_spe   n
1     A       0  39
2     A       1  32
3     B       0   3
4     B       1   2
5     C       0 115
6     C       1  24
7     D       0  11
8     D       1   3

我想添加一个新列fig$new,在 中添加数字fig$n,但仅在中的行fig$hands匹配时。

我需要保持数据框原样。

预期产出

> fig
  hands imp_spe   n   new
1     A       0  39    71 
2     A       1  32    71
3     B       0   3     5
4     B       1   2     5
5     C       0 115   139
6     C       1  24   139
7     D       0  11    14
8     D       1   3    14

我正在寻找解决方案dplyr

fig <- structure(list(hands = c("A", "A", "B", "B", "C", "C", "D", "D"
), imp_spe = c(0, 1, 0, 1, 0, 1, 0, 1), n = c(39L, 32L, 3L, 2L, 
115L, 24L, 11L, 3L)), row.names = c(NA, -8L), class = "data.frame")

标签: rdataframedplyrsummarize

解决方案


干得好

library(dplyr)

fig %>%
  group_by(hands) %>%
  mutate(new = sum(n)) %>%
  ungroup

推荐阅读