Applying by function to lm()

r

Solution

Try this instead:

tmp <- by(d, year, function(d.subset) lm(x~color, data=d.subset))

Problem

I am new to R and I am just learning about the `apply` functions and how they work. I simply want to extract the coefficients from a `lm` fit on a variable x by product color and brand across a several years. I know I can create a for loop and subset the data by model year and fit it, but I think its time I start using more built in functions, so I want to be able to do it with the by function or one of the apply functions. Here is what I was thinking. ``` #some made up data x<-rnorm(50,13400,1200) color<-sample(factor(c("Red","Black","Blue","Green","White")),50,replace=T) year<-sample(factor(2006:2012),50,replace=T) brand<-sample(factor(c("A","B","C","D")),50,replace=T) d<-data.frame(x,color,year,brand) #now I want to fit the model lm(x~color+brand) for each year level #this is what I was thinking... tmp<-with(d,by(x,year,function(y) lm(x~color,data=y))) sapply(tmp,coef) ``` Error in eval(predvars, data, env) : numeric 'envir' arg not of length one I am basing this off the exapmle R gave when I entered `help(by)`

Original source