Passing function argument to formula in R -


i'm trying understand why

foo = function(d,y,x) {     fit = with(d, lm(y ~ x)) } foo(mydata, y, x) 

won't work, instance

mydata = data.frame(y=rnorm(50), x=runif(50)) 

the bit seems tricky me passing arguments x , y formula, in lm(y ~ x).

@dmt's answer explains what's going on nicely.

here hoops jump through if want things work expect:

lmwrap <- function(d,y,x) {     ys <- deparse(substitute(y))     xs <- deparse(substitute(x))     f <- reformulate(xs,response=ys)     return(lm(f,data=d)) } mydata <- data.frame(x=1:10,y=rnorm(10)) lmwrap(mydata,y, x) 

this approach bit fragile, e.g. if pass arguments through function. also, getting "call" part of formula read y~x takes more trickery ...


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -