Home > Software design >  Curly curly - How to access the variable name
Curly curly - How to access the variable name

Time:09-29

I am trying to create a function which summarises a grouped dataset and then adds a column to identify which variable is being summarised (ID column).

I am not sure how to add the ID column using the curly curly appraoch.

my_fun <- function(dat, var_name){
  dat %>%
    mutate(id_column = names({{var_name}}))
}

my_fun(mtcars, cyl)

What I want is for the variable name, in this case cyl, to be recycled.

CodePudding user response:

Just, deparse/subsitute at the start

my_fun <- function(dat, var_name){
 nm1 <- deparse(substitute(var_name))
  dat %>%
    mutate(id_column = nm1)
}

-testing

my_fun(mtcars, cyl)
                  mpg cyl  disp  hp drat    wt  qsec vs am gear carb id_column
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4       cyl
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4       cyl
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1       cyl
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1       cyl
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2       cyl
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1       cyl
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4       cyl
Merc 240D           24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2       cyl
Merc 230            22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2       cyl
Merc 280            19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4       cyl
...

In the tidyverse, it may also be done directly from a symbol i.e. use ensym to convert to symbol and then evaluate (!!) to get the value or convert to string with as_string

my_fun <- function(dat, var_name){
  var_name <- rlang::ensym(var_name)
  dat %>%
    mutate(id_column = rlang::as_string(var_name), val_column = !! var_name)
}

-testing

my_fun(head(mtcars), cyl)
               mpg cyl disp  hp drat    wt  qsec vs am gear carb id_column val_column
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4       cyl          6
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4       cyl          6
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1       cyl          4
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1       cyl          6
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2       cyl          8
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1       cyl          6
  • Related