0

I have a dataframe in which I'd like to create a new column where each cell is formed by the sum of some other rows.

My dataframe would be like:

    Type    A    B    C
1     X     1    6    5
2     X     3    4    0
3     Y     4    1    0
4     Z     0    0    1

And my expected output:

    Type    A    B    C    D
1     X     1    6    5    12
2     X     3    4    0    7
3     Y     4    1    0    5
4     Z     0    0    1    1

I need to add the names of the columns I want to sum as a vector, such as c("A","B","C"), and I've tried functions such as rowSums and rowsum but they're not working properly.

MustardRecord
  • 305
  • 4
  • 14

1 Answers1

2

A possible solution with dplyr:

df <- tribble(
~"A", ~"B", ~"C",
1, 6, 5,
3, 4, 0,
4, 1, 0,
0, 0, 1
)

df %>% 
  rowwise() %>% 
  mutate(D = sum(c_across(A:C)))
Leonardo
  • 2,439
  • 33
  • 17
  • 31