3

Consider I have a dataframe, and want to compute the sum of two random columns.

I tried:

df <- data.frame(a=seq(1,3),b=seq(4,6),c=seq(7,9))
vars <- sample(letters[1:3],2)
df %>% rowwise() %>% mutate(s=sum({{vars}}))

But I get:

> df %>% rowwise() %>% mutate(s=sum({{vars}}))
Error in `.fun()`:
ℹ In argument: `s = sum(c("c", "b"))`.
ℹ In row 1.
Caused by error in `sum()`:
! invalid 'type' (character) of argument
Run `rlang::last_trace()` to see where the error occurred.

Because, although the vector is expanded, the strings inside it are not converted to symbols.

What would be the tidyverse way to do that?

1
  • I feel like this should be a duplicate but although I can find lots of similar questions about selecting variables dynamically in dplyr, I can't find an exact dupe. If someone can I'm happy to delete my answer and link to that. Commented Oct 28, 2024 at 12:13

3 Answers 3

3

You could use dplyr::c_across() here.

c_across() is designed to work with rowwise() to make it easy to perform row-wise aggregations

df |>
    rowwise() |>
    mutate(
        s = sum(c_across(all_of(vars)))
    )
# A tibble: 3 × 4
# Rowwise: 
#       a     b     c     s
#   <int> <int> <int> <int>
# 1     1     4     7     8
# 2     2     5     8    10
# 3     3     6     9    12

In this particular case I think it's simpler and certainly faster to just do:

df$s <- rowSums(df[vars])
# ^^ same result

However, I imagine your real desired use is more complex. You may want to check out the Per row-summary statistics section of the dplyr row-wise vignette.

Sign up to request clarification or add additional context in comments.

Comments

2

You could use !!!syms()

df %>%
    rowwise() %>%
    mutate(s = sum(!!!syms(vars)))

Comments

1

we can also use pick(all_of) and rowSums, so we keep efficency while still within dplyr. This obviates the need for rowwise()

df <- df %>%
    mutate(s = rowSums(pick(all_of(vars))))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.