0

Suppose I have a data frame with column a and b:

> library(dplyr)
> df <- data.frame(a=c(1,2,3),b=c(2,3,4))

  a b
1 2 2
2 3 3
3 4 4

Now there are two variables which refer to the column names in the data frame:

> col1 <- 'a'
> col2 <- 'b'

I want to use these variables to refer to the columns in dyplyr's mutate function rather than using the column names directly. The following code works:

> df %>% mutate(a=!!sym(col2))
  a b
1 2 2
2 3 3
3 4 4

However if I use unquote before the equal sign, it won't work:

> df %>% mutate(!!sym(var1) = !!sym(var2))

Error: unexpected '=' in "df %>% mutate(!!sym(var1) ="

So how do I make it work in this case? Thanks for any help.

Catiger3331
  • 611
  • 1
  • 6
  • 18
  • 2
    It should be `df %>% mutate(!!sym(var1) := !!sym(var2))`. You need `:=` if you want to dynamically name the parameter. – MrFlick Feb 05 '19 at 18:22
  • @MrFlick Thanks. It works. That was fast! I'll look into the reference question you added. – Catiger3331 Feb 05 '19 at 18:25
  • 1
    That's answered by this question: https://stackoverflow.com/q/26269423/2372064 It's an operator that R allows (but has no implementation for) and is used most commonly by dplyr and data.table but any package could redefine it. This particular usage would not work with base R functions. It's the "tidyverse" meaning that's used here. – MrFlick Feb 05 '19 at 18:27

0 Answers0