Reputation: 47
I have a list of 192 data frames, each data frame contains several variables. My objective is to run a regression for each data frame in the list and extract the intercept and the betas and append them into a new data frame, so I will have a data frame with 192 rows and one column with intercepts and several columns for betas.
The only approach I could run was the following:
# list with 192 lm objects #
reg_list = list()
# loop for running regressions and adding the results into the list #
for(i in 1:length(df)){
reg_list[[i]]= lm(x1 ~ x2 + x3 ,data=df[[i]])
}
# "df" is the list with the 192 data frames #
The issue here is that I have to extract the coefficients from this new list with another procedure, so I am looking a way to append the coefficients into a data frame directly in the same loop.
Thanks in advance for the help
Upvotes: 0
Views: 535
Reputation: 269586
This performs the regressions giving list reg
and then creates a matrix of coefficients with the ith column holding the ith set of coefficients. anscombe
is a data frame that comes with R that has x1, x2, x3 and others as column names.
dfs <- list(anscombe, anscombe) # list of data frames
reg <- lapply(dfs, lm, formula = x1 ~ x2 + x3)
sapply(reg, coef)
Upvotes: 3