Say I have something like:
# Create some data:
treatment <- round(runif(20, min = 0, max = 1),0)
d2 <- round(runif(20, min = 0, max = 1),0)
bxd2 <- treatment * d2
infection <- round(runif(20, min = 0, max = 100),0)
lung <- round(runif(20, min = 0, max = 100),0)
head <- round(runif(20, min = 0, max = 100),0)
df <- data.frame(treatment, d2, bxd2, infection, lung, head)
rm(treatment, d2, bxd2, infection, lung, head)
reg_func <- function(i,data){
form <- paste(colnames(df)[i+3], c("treatment + d2 + bxd2"), sep = "~")
form <- as.formula(form)
print(lm(form, data = data))
}
for (i in 1:3) {
name <- paste0("reg", i)
assign(name, reg_func(i, df))
}
Now this works the way I would like, I end up with reg1,...,regN assigned in the workspace (bad habit, but works well for econometrics).
My question is now: why would I want to turn (something like the above) into an apply instance? The for loop seems so easy, yet constanly I hear people saying "... you should really use [X]apply".