Search code examples
rdplyrnse

mixing constant and variable column names in dplyr::mutate/transmute


I am trying to change the class of a dataframe column using dplyr. The name of the target column is contained in a variable

my_df<-data.frame(colour=c("red","blue","green"),
                  val1=as.character(c(1,12,13)),
                  val2=c(21,22,23))

target_var="val1"

After some fiddling I managed to reach my goal using standard R subsetting:

my_df %>% transmute(colour = colour,
                 !!myval := as.numeric(.[,myval]))

But I suspect that there are less complex ways of referring to the target column, which is more consistent with other 'dplyr' expressions. I have tried solving this question with the information from the "Programming with dplyr" vignette, but no luck. Could anyone point me in the right direction?


Solution

  • We could use the sym to convert to symbol and then with !!

    my_df %>%
        transmute(colour = colour, 
            !!target_var := as.numeric(as.character(!!rlang::sym(target_var))))
    #    colour val1
    #1    red    1
    #2   blue   12
    #3  green   13
    

    NOTE: There the 'val1' is factor because by default stringsAsFactors = TRUE. So, we need to convert it to character and then to numeric

    data

    my_df<-data.frame(colour=c("red","blue","green"),
                  val1=as.character(c(1,12,13)),
                  val2=c(21,22,23))
    
    target_var <- "val1"