I'm new to R, and I just learn about functions applyand how they work. I just want to extract the coefficients from the set lmfor the variable x by product color and brand in a few years.
I know that I can create a for loop and a subset of the model year data and customize it, but I think it's time to use more built-in functions, so I want to be able to do this with a function or one of the applicable functions. Here is what I thought.
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)
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 1 long
I base this on exapmle R when I introduced help(by)
user1392795
source
share