I want call the predict function using different models to extract its predicted value.
I tried using paste0 to call the right model but it doesn't work
for example:
model0 = lm(mpg ~ cyl + disp, data = mtcars)
model1 = lm(mpg ~ hp + drat, data = mtcars)
model2 = lm(mpg ~ wt + qsec, data = mtcars)
testdat0 = data.frame(cyl = 6, disp = 200)
testdat1 = data.frame(hp = 100, drat = 4)
testdat2 = data.frame(wt = 4, qsec = 20)
res = NULL
for (i in 1:3) {
res = rbind(res, c(i-1, predict(paste0('model',i-1), newdata = paste0('testdat0',i-1))))
}
to do it manually
rbind(c(0, predict(model0, newdata = testdat0)),
c(1, predict(model1, newdata = testdat1)),
c(2, predict(model2, newdata = testdat2)))
1
[1,] 0 21.02061
[2,] 1 24.40383
[3,] 2 18.13825
Another way I thought of doing this was to put the models and testdata in 2 separate list() and use a for loop to call them but that also didn't work. Is there another way of doing this or am I doing something wrong.. TIA
c()it to an index number. Is this what you want to do?lm<-list(model0,model1,model2);lt<-list(testdat0,testdat1,testdat2);purrr::map2(lm,lt,predict)ormapply(predict, lm,lt)