Search code examples
rtidyrrlangquasiquotes

Using rlang::sym inside list definition


I'm writing an R script and I need to allow user to specify the name of variable that will be proccessed by hand, i.e.

var <- 'user_name'

Generally then I refer to that using rlang::sym and quoting/unquoting mechanism. However, I need to use tidyr::replace_na and none of my ideas worked here as the name of the variable has to be specified inside list.

How can I refer to my var in such a case? I was thinking about something like below:

data <- data %>% replace_na(list(sym(var) = 0))

But it didn't work...


Solution

  • We can also put replace_na inside mutate and unquote:

    library(dplyr)
    library(tidyr)
    
    var <- 'user_name'
    
    data %>%
      mutate(!!var := replace_na(!!sym(var), 0))
    

    Result:

      user_name
    1         0
    2         1
    3         2
    4         3
    5         4
    6         5
    

    Data:

    data <- data.frame(user_name = c(NA, 1:5))