5

Below I've written a simple function snafu() that calculates a new variable snafu_var.

library(dplyr)

df <- mtcars %>% select(am, cyl) %>% slice(1:5)

snafu <- function(data, var1, var2){
  require(dplyr)

  var1 <- enquo(var1)
  var2 <- enquo(var2)

  data %>% mutate(snafu_var = !!var1 + !!var2)
}

snafu(df, var1 = am, var2 = cyl)

Now I want to nest snafu() within another function foobar() that will utilize the variable created by snafu().

foobar <- function(data, var1, var2) {
  require(dplyr)

  data <- snafu(data, var1, var2)

  data %>% mutate(foo_var = snafu_var + 1)
}

foobar(df, var1 = am, var2 = cyl)

I'm struggling on two counts (probably related):

1) The nested function within foobar() can't seem to access the arguments supplied to foobar(), leading to the error message:

Error in mutate_impl(.data, dots) : 
  Evaluation error: object 'am' not found.

2) Once I get the nested function to work, how can I call it's output, snafu_var within the function foobar()?

This is just a reprex of a more complex nested function, but essential to solving my problem is that the functions be nested and the variable created by the nested function, snafu(), be utilized by the parent function, foobar().

Joe
  • 3,217
  • 3
  • 21
  • 37

1 Answers1

3

Use ... in foobar:

foobar <- function(data, ...) {

  data <- snafu(data, ...)

  data %>% mutate(foo_var = snafu_var + 1)
}
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • is there a way to pass the arguments along to snafu if they've been explicitly named in foobar? In your version of foobar(), it would be mysterious to know which arguments need to be named. – Joe Aug 29 '18 at 21:45