I am trying to write a function that calls another function that requires formula arguments. However, I'm not able to pass the y ~ x arguments to the inner function.
Without the wrapping function it works:
test.df <- data.frame("test.x" = c(1,1,1,2,2), "test.y" = 1:5)
my.result <-lm(data = test.df, formula = test.y ~ test.x)
But I want this to work:
example.function <- function(my.data, my.y){
my.result <- lm(data = my.data, formula = my.y ~ test.x)
return(my.result)
}
example.function(my.data = test.df, my.y = test.y)
# Error in eval(predvars, data, env) : object 'test.y' not found
example.function(my.data = test.df, my.y = "test.y")
# Error in model.frame.default(formula = my.y ~ test.x, data = my.data, :
# variable lengths differ (found for 'test.x')
I tried to use {{}}
but this also doesn't work:
example.function <- function(my.data, my.y){
my.result <- lm(data = my.data, formula = {{my.y}} ~ test.x)
return(my.result)
}
example.function(my.data = test.df, my.y = test.y)
# Error in eval(predvars, data, env) : object 'test.y' not found
example.function(my.data = test.df, my.y = "test.y")
# Error in model.frame.default(formula = { :
# variable lengths differ (found for 'test.x')
And I also tried to use enquo()
and !!
but this doesn't work either:
example.function <- function(my.data, my.y){
enquo(my.y)
my.result <- lm(data = my.data, formula = !! my.y ~ test.x)
return(my.result)
}
example.function(my.data = test.df, my.y = test.y)
# Error in eval(predvars, data, env) : object 'test.y' not found
example.function(my.data = test.df, my.y = "test.y")
# Error in !my.y : invalid argument type
Thank you for any help understanding this!