Search code examples
rdplyrtidyverserlangforcats

How to supply existing variable to mutate through reference?


Here is my data:

df <- tibble::tribble(
         ~A,  ~B,
        "C", "G",
        "D", "H",
        "E", "I",
        "F", "J")

df$A <- as.factor(df$A)

var <- "A"

And, I want to relevel A from C to E using, maybe rlang, something like this, but it's not working!

var <- syms(var)
df <- df %>% mutate(!!!var = fct_relevel(!!!var, "E"))

My desired output is:

df <- df %>% mutate(A = fct_relevel(A, "E"))
levels(df$A)

But instead of supplying A manually, I want to programmatically supply these, something in line rlang syms using var character vector.

How should I do that?


Solution

  • I agree with @alistaire's comment but for what it's worth, the correct rlang syntax would be:

    df <- df %>% mutate(!!var := fct_relevel(!!rlang::sym(var), "E"))
    levels(df$A);
    #[1] "E" "C" "D" "F"
    

    Sample data

    df <- tibble::tribble(
             ~A,  ~B,
            "C", "G",
            "D", "H",
            "E", "I",
            "F", "J")
    
    df$A <- as.factor(df$A)
    
    var <- "A"