3

In the spirit of similar questions along these lines here and here, I would like to be able to sum across a sequence of columns in my data_frame & create a new column:

df_abc = data_frame(
  FJDFjdfF = seq(1:100),
  FfdfFxfj = seq(1:100),
  orfOiRFj = seq(1:100),
  xDGHdj = seq(1:100),
  jfdIDFF = seq(1:100),
  DJHhhjhF = seq(1:100),
  KhjhjFlFLF = seq(1:100),
  IgiGJIJFG= seq(1:100),
)

# this does what I want
df_abc %>% 
  mutate(
    sum_1 = orfOiRFj + xDGHdj + jfdIDFF + DJHhhjhF
  ) 

Clearly, if there are a lot of variables in this sequence, typing them out is not feasible. Also, the names of the variables are not regex-friendly, so cannot be selected by a rule, other than the fact that they occur in a sequence.

I am hoping that there exists an abstraction in the tidyverse, that allows something like:

df_abc %>% 
  mutate(
    sum_1 = sum(orfOiRFj:DJHhhjhF)
  )

Thanks.

tchakravarty
  • 10,038
  • 10
  • 58
  • 107
  • 2
    This might be a duplicate of https://stackoverflow.com/questions/27354734. In my answer there I included an option that would translate to `df_abc %>% mutate(sum_1 = select(., orfOiRFj:DJHhhjhF) %>% rowSums())` for your answer – talat Dec 01 '17 at 10:16
  • 2
    Possible duplicate of [dplyr mutate rowSums calculations or custom functions](https://stackoverflow.com/questions/27354734/dplyr-mutate-rowsums-calculations-or-custom-functions) – h3rm4n Nov 26 '18 at 08:11

1 Answers1

14

You can use rowSums to do that:

# option 1
df_abc %>% mutate(sum_1 = rowSums(.[3:6]))
# option 2
df_abc %>% mutate(sum_1 = rowSums(select(.,orfOiRFj:DJHhhjhF)))

The result:

# A tibble: 100 x 9
   FJDFjdfF FfdfFxfj orfOiRFj xDGHdj jfdIDFF DJHhhjhF KhjhjFlFLF IgiGJIJFG sum_1
      <int>    <int>    <int>  <int>   <int>    <int>      <int>     <int> <dbl>
 1        1        1        1      1       1        1          1         1     4
 2        2        2        2      2       2        2          2         2     8
 3        3        3        3      3       3        3          3         3    12
 4        4        4        4      4       4        4          4         4    16
 5        5        5        5      5       5        5          5         5    20
 6        6        6        6      6       6        6          6         6    24
 7        7        7        7      7       7        7          7         7    28
 8        8        8        8      8       8        8          8         8    32
 9        9        9        9      9       9        9          9         9    36
10       10       10       10     10      10       10         10        10    40
# ... with 90 more rows
h3rm4n
  • 3,871
  • 13
  • 21