[R] lm weights argument within function
Daniel Caro
dcarov at gmail.com
Fri Aug 1 17:36:04 CEST 2014
Hi all,
I need to loop over "lm" within a function using "weights". For example:
mydata = data.frame(y=rnorm(100, 500, 100), x= rnorm(100),
group=rep(c(0,1), 50), myweight=1/runif(100))
reg.by.wt <- function(formula, wt, by, data) {
if(missing(by)) {
summary(lm(formula=formula, data=data, weights=data[[wt]]))
} else {
lapply(split(data, data[by]), function(i)
summary(lm(formula=formula, data=i, weights=data[[wt]])))
}
}
reg.by.wt(formula = y ~ x, by="group", data=mydata, wt="myweight")
Error in summary(lm(formula = formula, data = i, weights = data[[wt]])) :
error in evaluating the argument 'object' in selecting a method for
function 'summary': Error in eval(expr, envir, enclos) : object 'wt'
not found
The functions works if I change "weights=data[[wt]]" for
"weights=myweight", but I need wt to be an argument in quotes, not an
object. It seems the issue is related to ?lm = "All of weights, subset
and offset are evaluated in the same way as variables in formula, that
is first in data and then in the environment of formula., but I can't
figure it out. Can you please provide any advice? Thank you.
Daniel
More information about the R-help
mailing list