如何在组方面添加2列

时间:2019-10-09 12:20:31

标签: r dataframe

我想就组SAMPN分别添加列a和b sum.a和sum.b

输出:

SAMPN     a   b
 1        1   2
 1        3   5
 2        1   1
 2        7   4

输出

SAMPN     a   b     sum.a       sum.b
 1        1   2      4            7
 1        3   5      4            7
 2        1   1      8            5
 2        7   4      8            5

2 个答案:

答案 0 :(得分:1)

require(dplyr) 
data %>% group_by(SAMPN) %>%
  mutate(sum.a=sum(a),sum.b=sum(b))

# A tibble: 4 x 5
# Groups:   SAMPN [2]
  SAMPN     a     b sum.a sum.b
  <int> <int> <int> <int> <int>
1     1     1     2     4     7
2     1     3     5     4     7
3     2     1     1     8     5
4     2     7     4     8     5

答案 1 :(得分:1)

使用data.table

require(data.table)
setDT(dt)[,.(SAMPN=SAMPN,a=a,b=b,sum_a=sum(a),sum_b=sum(b)),by=.(SAMPN)]

   SAMPN SAMPN a b sum_a sum_b
1:     1     1 1 2     4     7
2:     1     1 3 5     4     7
3:     2     2 1 1     8     5
4:     2     2 7 4     8     5