0

I'd like to perform some programmatic changes to a large tibble/data frame in R. The suggestion through the dplyr programming vignette suggests to use a glue-like syntax (like {{...}}) together with :=. However, neither of the examples below result in what I want.

library(tidyverse)

some_var <- 'a'
df <- tibble(
  !!'a' := 1:3,
  Sum := !!some_var # <--- should yield 1:3 but yields c('a', 'a', 'a')
)

some_var <- 'b'
df <- tibble(
  !!'a' := 1:3,
  Sum := a
) %>% mutate(
  b = 1:3,
  Sum := Sum + !!some_var # <--- should yield 1:3 + 1:3 = c(2, 4, 6), but fails
)

The second example is different from the first in that the error seems to group Sum and !!some_var into a single column called `Sum + 'b'`:

Error: Problem with `mutate()` input `Sum`.
x non-numeric argument to binary operator
i Input `Sum` is `Sum + "b"`.

How can I achieve my desired result using the variable names (some_var) above?

Werner
  • 14,324
  • 7
  • 55
  • 77
  • If you have a string, use the `.data` pronoun. For example `Sum = .data[[some_var]]` and `Sum := Sum + .data[[some_var]]`. The `!!` expects symbols, not strings. This was included in the "Indirection" section of the dplyr programming guide you linked to. – MrFlick Dec 22 '20 at 21:28
  • @MrFlick: Woah! That slipped my reading and is now clear. Thanks! – Werner Dec 22 '20 at 21:48

0 Answers0