1

How do I mutate a field when concatenating the name of the field?

library(tidyverse)    
x <- "blah"
y <- "cyl"

mtcars %>% 
  mutate(paste0(x,y) := as.factor(cyl)) # "Error: The LHS of `:=` must be a string or a symbol"

mtcars %>% 
  mutate(paste0(x,y) = as.factor(cyl)) # Error: unexpected '=' in: "mtcars %>%  mutate(paste0(x,y) ="

How ca I end up with a new field called 'blahcyl' that is a factor of cyl?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

1 Answers1

6

Evaluate the string with !!

library(dplyr)
mtcars %>% mutate(!!paste0(x,y) := as.factor(cyl))

#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb blahcyl
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4       6
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4       6
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1       4
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1       6
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2       8
#...
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks, that does work now that I tried it, accepting when the time limit comes off. I did try `!! rlang::sym(paste0(x,y))` before posting. How/when to use just `!!` and then when to use `!! rlang::sym()`? – Doug Fir Feb 20 '20 at 01:50
  • 2
    I'm not sure if this always is the case but in general if you want to add new column with name `string` use `!!string := ` and if you want to use `string` as column name to do any operation use `!!sym(string)`. – Ronak Shah Feb 20 '20 at 01:57
  • When do you need to use !!paste0(x,y) and when !!sym(paste0(x,y)) ? – skan Mar 24 '22 at 16:16