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()
.
Use ... in foobar:
foobar <- function(data, ...) {
data <- snafu(data, ...)
data %>% mutate(foo_var = snafu_var + 1)
}