[R] Formula in lm inside lapply

Li, Yan (IED) Yan.Y.Li at MorganStanley.com
Wed Aug 15 18:16:12 CEST 2007

I am trying to run separate regressions for different groups of
observations using the lapply function. It works fine when I write the
formula inside the lm() function. But I would like to pass formulae into
lm(), so I can do multiple models more easily. I got an error message
when I tried to do that. Here is my sample code:

#generating data
x1 <- rnorm(100,1)
x2 <- rnorm(100,1)
y  <- rnorm(100,1)
group <- rep(c("A","B"),c(40,60))
group <- factor(group)
df <- data.frame(y,x1,x2,group)

#write formula inside lm--works fine
res1 <- lapply(levels(df$group), function(x) lm(y~x1,df, subset = group
res2 <- lapply(levels(df$group),function(x) lm(y~x1+x2,df, subset =
group ==x))

#try to pass formula into lm()--does not work
formula1 <- as.formula(y~x1)
formula2 <- as.formula(y~x1+x2)
resf1 <- lapply(levels(df$group),function(x) lm(formula1,df, subset =
group ==x))
resf2 <- lapply(levels(df$group),function(x) lm(formula2,df, subset =
group ==x))

The error message is 
'Error in eval(expr, envir, enclos): object "x" not found'

Any help is greatly appreciated!


This is not an offer (or solicitation of an offer) to buy/se...{{dropped}}

More information about the R-help mailing list