R: Evaluate an expression in a data frame with arguments that are passed as an object -
i want write function evaluates expression in data frame, 1 using expressions may or may not contain user-defined objects. think magic word "non-standard evaluation", cannot quite figure out yet.
one simple example (yet realistic purposes): say, want evaluate lm()
call variables found in data frame.
mydf <- data.frame(x=1:10, y=1:10)
a function can written follows:
f <- function(df, expr){ expr <- substitute(expr) pf <- parent.frame() eval(expr, df, pf) }
such want using following command.
f(mydf, lm(y~x)) # call: # lm(formula = y ~ x) # # coefficients: # (intercept) x # 1.12e-15 1.00e+00
nice. however, there cases in more convenient save model equation in object before calling lm()
. unfortunately above function no longer it.
fml <- y~x f(mydf, lm(fml)) # error in eval(expr, envir, enclos): object 'y' not found
can explain why second call doesn't work? how function altered, such both calls lead desired results? (desired=fitted model)
cheers!
from ?lm
, re data
argument:
if not found in data, variables taken environment(formula)
in first case, formula created in eval(expr, df, pf)
call, environment of formula environment based on df
. in second case, formula created in global environment, why doesn't work.
because formulas come own environment, can tricky handle in nse.
you try:
with(mydf, { print(lm(y~x)) fml <- y~x print(lm(fml)) } )
but isn't ideal you. short of checking whether names in captured parameter resolve formulas, , re-assigning environments, you'll have trouble. worse, isn't obvious re-assigning environment right thing do. in many cases, want in formula environment.
there loosely related discussion on issue on r chat:
Comments
Post a Comment