I'm trying to use the pred function with a list but it seems that I have a problem. When I compute it it is written:
Error : $ operator is invalid for atomic vectors
This is my code:
for (i in 1:30) {
a=i
print(a)
df[,4][df[,1]==a] <- exp(predict.lm(summary_of_lm[[a]][1], newdata = df[df[,1]==a,])) }
I want to iterate a prediction for the regression I made over 30 years. Those are stocked in a list summary_of_lm that is: summary_year_1, summary_year_2 ... Those are the matrix that stocked the coefficient, std errors etc... What I don't understand is that I am not using the $ sign and I have this error.
> class(summary_of_lm)
[1] "list"
> class(summary_of_lm[[a]])
[1] "matrix"
Detail: I also already declared all the parameters with the same variable name for df and summary_year_i in order to make the pred works.
I am not sure if you are looking for this where a
below is the list of all datasets(for your example it can be like for year 1995,1996 and so on)
a<-split(mydata,mydata$cyl)
myprediction<-Map(function(x)predict(lm(mpg~cyl,data=x)),a)
> myprediction
$`4`
Datsun 710 Merc 240D Merc 230 Fiat 128 Honda Civic Toyota Corolla Toyota Corona
26.66364 26.66364 26.66364 26.66364 26.66364 26.66364 26.66364
Fiat X1-9 Porsche 914-2 Lotus Europa Volvo 142E
26.66364 26.66364 26.66364 26.66364
$`6`
Mazda RX4 Mazda RX4 Wag Hornet 4 Drive Valiant Merc 280 Merc 280C Ferrari Dino
19.74286 19.74286 19.74286 19.74286 19.74286 19.74286 19.74286