问题
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