I am trying to create a function or even just work out how to run a loop using data.table syntax where I can subset the table by factor, in this case the id variable, then r
> df <- data.frame(id = letters[1:3],
+ cyl = sample(c("a","b","c"), 30, replace = TRUE),
+ factor = sample(c(TRUE, FALSE), 30, replace = TRUE),
+ hp = sample(c(20:50), 30, replace = TRUE))
> by(df,df$id,function(x) lm(hp ~ cyl + factor, data = x))
df$id: a
Call:
lm(formula = hp ~ cyl + factor, data = x)
Coefficients:
(Intercept) cylb cylc factorTRUE
41.571 4.143 -3.429 -5.571
------------------------------------------------------------------------------------------
df$id: b
Call:
lm(formula = hp ~ cyl + factor, data = x)
Coefficients:
(Intercept) cylb cylc factorTRUE
46.040 -1.133 -19.467 -7.720
------------------------------------------------------------------------------------------
df$id: c
Call:
lm(formula = hp ~ cyl + factor, data = x)
Coefficients:
(Intercept) cylc factorTRUE
31.850 3.917 -8.200
enter code here