I\'m trying to understand why
foo = function(d,y,x) {
fit = with(d, lm(y ~ x))
}
foo(myData, Y, X)
won\'t work, where for instance
@DMT's answer explains what's going on nicely.
Here are the hoops to jump through if you want things to work as you 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)
Or it can be simplified a bit if you pass the column names as strings rather than symbols.
lmwrap <- function(d,y,x) {
f <- reformulate(xs, response=ys)
return(lm(f, data=d))
}
lmwrap(mydata, "Y", "X")
This approach will be a bit fragile, e.g. if you pass arguments through another function. Also, getting the "Call" part of the formula to read Y~X
takes more trickery ...