Skip to content
Back to formatted view

Raw Message

Message-ID: <CAMeQTh0DWYRAsN6Su2f1rAG9BDVPLH9sqjxnb=eJt+v82omhww@mail.gmail.com>
Date: 2014-08-01T15:36:04Z
From: Daniel Caro
Subject: lm weights argument within function

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