0

My data frame looks something like this

USER OBSERVATION COUNT.1 COUNT.2 COUNT.3
A    1           0       1       1
A    2           1       1       2
A    3           3       0       0

With dplyr I want to build a columns that sums the values of the count-variables for each row, selecting the count-variables based on their name.

USER OBSERVATION COUNT.1 COUNT.2 COUNT.3 SUM
A    1           0       1       1       2
A    2           1       1       2       4
A    3           3       0       0       3

How do I do that?

TIm Haus
  • 221
  • 1
  • 8

1 Answers1

2

As you asked for a dplyr solution, you can do:

library(dplyr)

df %>% 
  mutate(SUM = rowSums(select(., starts_with("COUNT"))))

  USER OBSERVATION COUNT.1 COUNT.2 COUNT.3 SUM
1    A           1       0       1       1   2
2    A           2       1       1       2   4
3    A           3       3       0       0   3
27 ϕ 9
  • 17,064
  • 3
  • 26
  • 36