0
votes

I am trying to figure out how to make a for loop that does a regression 10 times and then puts it in an 10x11 matrix.

Here is the code I am using and for some reason it is not working...

for (i in 1:10) {
 Pwdlm.list[[i]] = 
 lm(Pwd[,9+i]~logwprice1+logwprice2+logwprice3+logwprice4+
    logwprice5+logwprice6+logwprice7+logwprice8+logwprice9+logwprice10+
    Pwd$storeid, data=Pwd)
}
Pwdmat = matrix(Pwdlm.list[[i]]$coefficients, nrow = 10, ncol = 11)

I keep getting this warning:

Warning message: In matrix(Pwdlm.list[[i]]$coefficients, nrow = 10, ncol = 11) : data length [25] is not a sub-multiple or multiple of the number of rows [10]

But I need the data to fit in to 10 rows.

I understand it is hard without seeing the data but I am unsure if it has something to do with the [,9+i]

1
This does not explicitly answer your question, but I think it might be useful and somewhat more efficient: stackoverflow.com/a/35638859/2378649 To make it work in your setting (the dplyr part, that is), you probably need to melt your dataframe and create a grouping variable.coffeinjunky
When asking for help, please include a minimal reproducible example with sample input data so we can copy/paste the code to get the same error. This makes it much easier to help you. It seems like you are getting many more than 10 coefficients. Have you run it without the loop to verify it works as expected? Are all yours columns numeric?MrFlick
Thanks. Sorry was my first post. I will get back to y'all as soon as I can try these methods. I like the sapply idea and will try it. I do have a grouping variable though. But yes I am getting 25 rows instead of 10.Tony Tafoya

1 Answers

0
votes

Appears you were not getting an error from the lm-call or the assignment to Pwdlm.list. Try this instead:

 Pwdmat = sapply(Pwdlm.list, coefficients)

The sapply function attempts returning a matrix when the lengths of the all the returned values are equal. The values for each regression will each be in a column, and it appears that is the form you are hoping to get.