Skip to content
Prev 342774 / 398506 Next

lm weights argument within function

One way to accomplish this is to assign a new environment to the
formula, an environment which inherits from the formula's original
environment but one that you can add things to without affecting the
original environment.  Also, since you do this in a function only the
copy of the formula in the function is affected; when the function is
done your formula is not changed.  E.g.,

mydata <- data.frame( # a dataset that one can recreate
    y = log2(1:100),
    x = 1:100,
    group = rep(c(0,1), each = 50),
    myweight = 1/(1:100),
    yourweight = 1:100)

reg.by.wt <- function(formula, wt, by, data) {
  newEnv <- new.env(parent = environment(formula))
  newEnv$wt <- wt
  newEnv$data <- data
  environment(formula) <- newEnv
  if(missing(by)) {
    summary(lm(formula = formula, data = data, weights = data[[wt]]))
  } else {
    lapply(split(data, data[by]),
           function(i) {
               newEnv$i <- i
               summary(lm(formula = formula, data = i, weights = i[[wt]]))
           })
  }
}

try(reg.by.wt(formula = y ~ x, by="group", data=mydata, wt="myweight"))
try(reg.by.wt(formula = y ~ x, data=mydata, wt="myweight"))
try(reg.by.wt(formula = y ~ x, by="group", data=mydata, wt="yourweight"))

There may be less sneaky ways of doing this sort of thing.


Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Fri, Aug 1, 2014 at 8:36 AM, Daniel Caro <dcarov at gmail.com> wrote: