I have a data frame containing a vector of x values, a vector of y values, and an identifier vector:
x <- rep(0:3, 3) y <- runif(12) ID <- c(rep("a", 4), rep("b", 4), rep("c", 4)) df <- data.frame(ID=ID, x=x, y=y)
I would like to create a separate lm for a subset of x and y having the same identifier. The following code does the job:
a.lm <- lm(x~y, data=subset(df, ID=="a")) b.lm <- lm(x~y, data=subset(df, ID=="b")) c.lm <- lm(x~y, data=subset(df, ID=="c"))
Except that it is very fragile (there may be different identifiers in future data sets) and without vectorization. I would also like to keep all lms in one data structure. There must be an elegant way to do this, but I cannot find it. Any help?
source share