Roberto Tedesco
Roberto Tedesco

Reputation: 41

How to create a loop for a linear model in R

I am here to ask your help. I have to run a series of OLS regression on multiple depended variable using the same set for the independent ones.

I.e. I have a dataframe of size (1510x5), in particular each one represent the return of a portfolio, and I would like to regress it agains the same set of dependent variable (1510x4), which in my case are the factors from the Carhart model. Since, beside the value for the coefficients, I am interested in both their P-value and on the R2 of the regression, is there a way to build a loop that allows me to store the information?

What I have tried so far is:

for (i in 1:ncol(EW_Portfolio)) {
  lmfit <- lm(EW_Portfolio[, i] ~ FFM)
  summary(lmfit_i)
}

in the hope that, every time the loop repeated itself, I could see the result of each individual regression.

Upvotes: 1

Views: 7839

Answers (2)

Seyma Kalay
Seyma Kalay

Reputation: 2859

it may be something like, couldn't sure about the p.values

data("mtcars")

formulas <- list(
  mpg ~ disp,
  mpg ~ disp + wt
)

res <- vector("list", length = length(formulas))
my.r2 <- vector("list", length = length(formulas))
my.sum <- vector("list", length = length(formulas))

for(i in seq_along(formulas)){
  res[[i]] <- lm(formulas[[i]], data = mtcars)
  my.r2[[i]] <- (summary(res[[i]]))$adj.r.squared
  my.sum[[i]] <- (summary(res[[i]]))
  }
res
unlist(my.r2)
my.sum

lapply(formulas, lm, data = mtcars)

Upvotes: 1

lmo
lmo

Reputation: 38500

The easiest would be to store it in a list:

resultsList <- list()

for (i in 1:ncol(EW_Portfolio)) {
  lmfit <- lm(EW_Portfolio[, i] ~ FFM)
  resultsList[[i]] <- summary(lmfit_i)
}

You can then access the results you mention:

resultsList[[1]]$coefficients
resultsList[[1]]$r.squared

Upvotes: 1

Related Questions