How to extract coefficients outputs from a linear regression with loop

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 08:48:32

问题


I would like to know how I can loop a regression n times, and in each time with a different set of variables, extract a data.frame where each column is a regression and each row represent a variable.

In my case I have a data.frame of:

dt_deals <- data.frame(Premium=c(1,3,4,5),Liquidity=c(0.2,0.3,1.5,0.8),Leverage=c(1,3,0.5,0.7))

But I have another explanatory dummy variable called hubris, that is the product of a binomial distribution, with 0.25 of mean. Like that:

n <- 10 
hubris_dataset <- data.frame(replicate(n, rbinom(4,1,0.25))

In this sense, what I need is to make n simulation of hubris, so I can, make n regression each one with a different set of random binomial distribution and the output of each distribution needs to be put in a data.frame So far I could reach this:

# define n as the number of simulations i want
n=10
# define beta as a data.frame to put every coefficient from the lm regression
beta=NULL

for(i in 1:n) {
  dt_deals2 <- dt_deals
  beta[[i]] <- coef(lm(dt_deals$Premium ~ dt_deals$Liquidity + dt_deals$Leverage + hubris_dataset[,i], data=dt_deals2))
  beta <- cbind(reg$coefficients)
}

But this way it only generate the first set of coefficient, and doesn't make another ten columns for the data.frame.


回答1:


@jogo give an idea to change the for-loop method and use sapply, and change the object beta to list(). This was the result:

beta <- sapply(1:n, function(i) coef(lm(Premium ~ Liquidity +Leverage+ hubris_dataset[,i], data=dt_deals2)))

And it worked



来源:https://stackoverflow.com/questions/35483832/how-to-extract-coefficients-outputs-from-a-linear-regression-with-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!