I am writing loops or functions in R, and I still haven't really understood how to do that. Currently, I need to write a loop/function (not sure which one would be better) to create several linear regression models within the same data frame.
I have data like this:
dataset <- read.table(text =
"ID A_2 B_2 C_2 A_1 B_1 C_1 AGE
M1 10 6 6 8 8 9 25
M2 50 69 54 67 22 44 16
M3 5 80 44 78 5 55 18
M4 60 70 52 89 3 56 28
M5 60 5 34 90 80 56 34
M6 55 55 67 60 100 77 54", header = TRUE, stringsAsFactors = FALSE)
I am building models like this:
model1 <- lm(A_2~A_1+age, data=dataset)
model2 <- lm(B_2~B_1+age, data=dataset)
model3 <- lm(C_2~C_1+age, data=dataset)
I need to write a loop which:
- takes
variable _2
(the dependent variable) andvariable _1
(independent variable) and covariates likeage
... - creates the
lm
models, and stores outputs (i.e, T-value, p-value, confidence intervals etc) in a data.frame that I can then print.
Dep_va Ind_var Convarites Pvalue "upper.cI" "low.cI"
A_2 A_1 age
B_2 B_1 age
C_2 C_1 age
D_2 D_1 age