Home > Software engineering >  How to create an R function that doesn’t need ‘$’ specified for columns
How to create an R function that doesn’t need ‘$’ specified for columns

Time:10-11

Somewhat new to programming and I want to try to make a custom function made in R easier to use, and less redundant.

How do I go from a custom function looking like this when in use:

Function(data=df, x=df$x, y=df$y)

Into:

Function(data=df, x=x, y=y)

As my function definition looks something like this now:

Function <- function(data, x, y){ does whatever… }

Specifically, I don’t want to have to use the $ operator for every variable input. I just want to use the df I have as an argument for ‘data’. How would I set it up differently?

Thanks!

CodePudding user response:

You can Go with enqouting your arguments something like this

sum2vars <- function(data, x, y) {
  x <- rlang::ensym(x)
  y <- rlang::ensym(y)
  
  data[[x]]   data[[y]]
}

sum2vars(mtcars, mpg, am)
#>  [1] 22.0 22.0 23.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
#> [16] 10.4 14.7 33.4 31.4 34.9 21.5 15.5 15.2 13.3 19.2 28.3 27.0 31.4 16.8 20.7
#> [31] 16.0 22.4

Within the tidyverse you can use the embracing approach

plot2vars <- function(data, x, y) {
  ggplot2::ggplot(data, ggplot2::aes(x = {{ x }}, y = {{ y }}))  
    ggplot2::geom_point()
}

plot2vars(mtcars, wt, mpg)

For more details condiering reading the chapeter 19 of the book Advance R

And this post on programming in the tidyverse

Created on 2022-10-10 with reprex v2.0.2

  •  Tags:  
  • r
  • Related