2

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!

3
  • 2
    If both x and y are derived from the same df, perhaps there is no need to supply all 3 arguments to the function? Just use function(data = df), then use df$x and df$y inside the function? Commented Oct 10, 2022 at 21:39
  • @neilfws That’s a good idea, but I need to have x and y inputs flexible. Commented Oct 10, 2022 at 21:48
  • 1
    @DylanG But that is the way to make it flexible. If you pass a df to a function, you will always be able to access its columns. You can also pass the column names as strings and access df[[x]] and df[[y]]. Or pass the symbols and use non-standard evaluation. Commented Oct 10, 2022 at 21:52

1 Answer 1

4

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 consider reading the chapter 19 of the book Advance R

And this post on programming in the tidyverse

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

Sign up to request clarification or add additional context in comments.

1 Comment

Does exactly what I needed it to. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.