Output of a loop as a data.frame

Dear,
I'm using a loop (for) to generate many linear models, and I'm have a problem with output of the parameters.
I need of the parameters (Interceptor, R squared and angular) within in a data.frame to each model, but I only did can done the output as a list.
Follow below my code:

library(readxl)

precipitacao <- read_excel("preenchimento_falhas.xlsx", 
                                   col_types = c("numeric", "numeric", "numeric", 
                                                 "numeric", "numeric"))

parameters <- numeric()
for (i in 3:ncol(precipitacao)) {
  reglin <- lm(as.matrix(precipitacao[,2]) ~ as.matrix(precipitacao[,i]),
               data = precipitacao)
  r_sqrd <- summary.lm(reglin)$r.squared
  a_b <- coefficients(reglin)
  parameters[i] <- data.frame(c(r_sqrd,a_b))
}

How I can do this? Put the output for each model (each reglin) as a data.frame? I know that is banal, but, I'm learning yet.

My bests regards, and thank you guys!

I think you are looking for something like this:

dataset <- mtcars[3:7]

parameters <- data.frame(index = seq_len(ncol(x = dataset) - 2),
                         r_sqrd = NA,
                         a = NA,
                         b = NA)

for (i in 3:ncol(x = dataset))
{
  reglin <- lm(dataset[, 2] ~ dataset[, i])
  r_sqrd <- summary(object = reglin)$r.squared
  a_b <- coefficients(object = reglin)
  parameters[i - 2, -1] <- c(r_sqrd, a_b)
}

parameters
#>   index    r_sqrd          a         b
#> 1     1 0.2013847 353.652526 -57.54523
#> 2     2 0.4339488  -1.820922  46.16005
#> 3     3 0.5015804 631.703755 -27.17368

Created on 2019-05-18 by the reprex package (v0.3.0)

Obviously, I didn't have your data set, so had to use a existing one and I chose mtcars. Here, I stored the r^2, a and b of each model in a row. If you want, you can store in columns too.

1 Like

Dear @Yarnabrina,
Your proposition solved my problem.
Thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.