Search code examples
rdplyrrlang

rowwise() sum with vector of column names in dplyr


I am once again confused about how to achieve this:

Given this data frame:

df <- tibble(
  foo = c(1,0,1),
  bar = c(1,1,1),
  foobar = c(0,1,1)
)

And this vector:

to_sum <- c("foo", "bar")

I would like to get the row-wise sum of the values in the columns to_sum.

Desired output:

# A tibble: 3 x 4
# Rowwise: 
    foo   bar foobar   sum
  <dbl> <dbl>  <dbl> <dbl>
1     1     1      0     2
2     0     1      1     1
3     1     1      1     2

Typing it out works (obviously).

df %>% rowwise() %>% 
  mutate(
    sum = sum(foo, bar)
  )

This does not:

df %>% rowwise() %>% 
  mutate(
    sum = sum(to_sum)
  )

Which I understand, because if I were to try:

df %>% rowwise() %>% 
  mutate(
    sum = sum("foo", "bar")
  )

How can I compute the row-wise sum from a vector of column names?


Solution

  • I think you are looking for rlang::syms to coerce strings to quosures:

    library(dplyr)
    library(rlang)
    df %>% 
      rowwise() %>% 
      mutate(
        sum = sum(!!!syms(to_sum))
      )
    #     foo   bar foobar   sum
    #   <dbl> <dbl>  <dbl> <dbl>
    # 1     1     1      0     2
    # 2     0     1      1     1
    # 3     1     1      1     2