May
May

Reputation: 11

Can't find the object while using double curly brackets in the function

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

Answers (1)

akrun
akrun

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

enter image description here


If we want to use rlang then an optino is to convert to symbol 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

Related Questions