Home > Software design >  passing column names in functions as strings and evaluate with mutate
passing column names in functions as strings and evaluate with mutate

Time:11-08

I see gobs of posts about passing column names as strings to function but none of them consider this use case. All the methods I see don't work. Here is one. Please compare the what_I_want column to the what_I_get column below. I want the value of items in the column, not the column name, of course. Thanks.

library(dplyr)
Fun <- function(df,column) {
   df %>%
      mutate(what_I_want = cyl) %>% 
      # current best practice?  Doen't work in this case.
      mutate(what_I_get := {{column}})
}

mtcars[1:2,1:3] %>% Fun("cyl")
#>               mpg cyl disp what_I_want what_I_get
#> Mazda RX4      21   6  160           6        cyl
#> Mazda RX4 Wag  21   6  160           6        cyl

Created on 2022-11-07 with reprex v2.0.2

CodePudding user response:

Just add get

Fun <- function(df,column) {
df %>%
  mutate(what_I_want = get(column) )
}

mtcars[1:2,1:3] %>% Fun("cyl")
             mpg cyl disp what_I_want
Mazda RX4      21   6  160           6
Mazda RX4 Wag  21   6  160           6

CodePudding user response:

We may use ensym which can take both quoted as well as unquoted column name

Fun <- function(df,column) {
   df %>%
      mutate(what_I_want = !! rlang::ensym(column)) 
    
}

-testing

> mtcars[1:2,1:3] %>% Fun("cyl")
              mpg cyl disp what_I_want
Mazda RX4      21   6  160           6
Mazda RX4 Wag  21   6  160           6
> mtcars[1:2,1:3] %>% Fun(cyl)
              mpg cyl disp what_I_want
Mazda RX4      21   6  160           6
Mazda RX4 Wag  21   6  160           6

CodePudding user response:

Using the .data pronoun you could do:

library(dplyr)

Fun <- function(df,column) {
  df %>%
    mutate(what_I_get = .data[[column]])
}

mtcars[1:2,1:3] %>% 
  Fun("cyl")
#>               mpg cyl disp what_I_get
#> Mazda RX4      21   6  160          6
#> Mazda RX4 Wag  21   6  160          6

For more on the .data pronoun see Data mask programming patterns.

  • Related