Reputation: 16607
I'm creating a package that uses non-standard evaluation to keep track of the meaning of columns. The package passes a data frame among functions, which do various things do the same set of columns. Nonstandard evaluation works great for this:
my_select <- function(df, xcol, ycol) {
new_df <- dplyr::select(df, !!xcol, !!ycol)
new_df
}
my_select(mtcars, quo(wt), quo(mpg))
However, I'd like a function that works with a formula:
my_lm <- function(df, xcol, ycol) {
new_lm <- lm(!!xcol, !!ycol, data=df)
new_lm
}
my_lm(mtcars, quo(wt), quo(mpg)
returns Error in !xcol : invalid argument type
. I've tried all sorts of combinations of quo()
, enquo()
, and !!
, but the basic problem is that I don't know what kind of object lm
needs.
Upvotes: 2
Views: 357
Reputation: 1502
@zlipp gave a working answer, but here is a more updated version
my_lm <- function(df, xcol, ycol) {
xcol_e <- rlang::enquo(xcol)
ycol_e <- rlang::enquo(ycol)
form <- paste0(rlang::as_label(ycol_e), "~", rlang::as_label(xcol_e))
new_lm <- lm(form, data=df)
new_lm
}
my_lm(mtcars, wt, mpg)
my_lm <- function(.df, xcol, ycol) {
form <- rlang::new_formula(rlang::ensym(ycol), rlang::ensym(xcol))
new_lm <- lm(form, data=.df)
new_lm
}
my_lm(mtcars, wt, mpg)
Upvotes: 1
Reputation: 801
You can create a formula by pasting the values of the equation together, then pass the formula to lm
. I'm sure there's a better way to do this, but here's one working approach:
library(rlang)
my_lm <- function(df, xcol, ycol) {
form <- as.formula(paste(ycol, " ~ ", xcol)[2])
my_lm <- lm(form, data=df)
my_lm
}
my_lm(mtcars, quo(wt), quo(mpg))
#>
#> Call:
#> lm(formula = form, data = mtcars)
#>
#> Coefficients:
#> (Intercept) wt
#> 37.285 -5.344
Upvotes: 2