Reputation: 11
I was trying to write a function using {{}} to pass variables. Codes are below:
diagnostic <- function(data, x, y){
model <- lm({{y}}~{{x}}, data=data)
par(mfrow=c(2,2))
plot(model)
}
And when I wanted to use this function, I typed
diagnsoic(mydata, x=exer_past_mvpa, y=visuospatial_constructional_index_score_ch)
Both are the existing variable names in my dataset. However, I got this error:
Error in eval(predvars, data, env) :
object 'visuospatial_constructional_index_score_ch' not found
Would appreciate any advice here! Packages tidyverse
, dplyr
, rlang
were loaded.
Thanks, May
Upvotes: 1
Views: 86
Reputation: 887501
We may do this in base R
with reformulate
and deparse/substitute
diagnostic <- function(data, x, y){
y <- deparse(substitute(y))
x <- deparse(substitute(x))
fmla <- reformulate(x, response = y)
model <- lm(fmla, data=data)
par(mfrow=c(2,2))
plot(model)
}
-testing
diagnostic(mtcars, cyl, mpg)
-output
If we want to use rlang
then an optino is to convert to sym
bol and evaluate (!!
)
diagnostic <- function(data, x, y){
model <- rlang::inject(lm(!! rlang::ensym(y)~!! rlang::ensym(x), data=data))
par(mfrow=c(2,2))
plot(model)
}
diagnostic(mtcars, cyl, mpg)
Upvotes: 2