I want to write a custom function mylm
using the nonstandardized evaluation (NSE) in the rlang
package, which should output the same thing as running lm(cyl~ mpg, data = mtcars)
directly.
But I tried two different methods of NSE is an error, how can I run successfully mylm
function.
I know I can use reformatele ()
function to construct a formula
in mylm
function, but I want to know if I could use {{}}
,!!
Or inject()
to make mylm
run successfully.
# use{{}} for NSE
mylm <- function(y, x, data) {
lm({{ y }}, {{ x }}, data = data)
}
# use inject for NSE
mylm(cyl, mpg, data = mtcars)
#> Error in eval(expr, envir, enclos): object 'cyl' not found
mylm2 <- function(y, x, data) {
rlang::inject(lm({{ y }}, {{ x }}, data = data))
}
mylm2(cyl, mpg, data = mtcars)
#> Error in xj[i]: invalid subscript type 'language'
Created on 2023-12-15 with reprex v2.0.2
I've run into a similar issue and, for me, the best workaround was to use:
mylm <- function(y, x, data) {
lm(data[[y]] ~ data[[x]], data = data)
}
mylm("cyl", "mpg", data = mtcars)
#>
#> Call:
#> lm(formula = data[[y]] ~ data[[x]], data = data)
#>
#> Coefficients:
#> (Intercept) data[[x]]
#> 11.2607 -0.2525
Created on 2023-12-15 with reprex v2.0.2
Would that work for your use-case? Or do you want/need to use NSE for some other reason?