0
dd <- data.frame(a=1:10,b=2:11,c=3:12)
dd %>% mutate( Total=rowSums(.[1:2]))
    a  b  c CCI
1   1  2  3   3
2   2  3  4   5
3   3  4  5   7
4   4  5  6   9
5   5  6  7  11
6   6  7  8  13
7   7  8  9  15
8   8  9 10  17
9   9 10 11  19
10 10 11 12  21

Is there a way to select the variable names like a:b ? I have hundreds of variables but the position may change with another version of dataset; so the safe way is to select variables by styles like a:b?

Z. Zhang
  • 637
  • 4
  • 16

1 Answers1

1

In dplyr 1.0.0 You can use rowwise and c_across:

dd %>%  rowwise %>% mutate(Total = sum(c_across(a:b))) %>% ungroup
       a     b     c Total
   <int> <int> <int> <int>
 1     1     2     3     3
 2     2     3     4     5
 3     3     4     5     7
 4     4     5     6     9
 5     5     6     7    11
 6     6     7     8    13
 7     7     8     9    15
 8     8     9    10    17
 9     9    10    11    19
10    10    11    12    21
Waldi
  • 39,242
  • 6
  • 30
  • 78