# For循环调用不同的函数变量

##### 问题描述投票：0回答：2

``````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))))
}
``````

``````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
``````

r
##### 2个回答
2

``````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)

#make list from sample data
data <- list(dat0=list(model=model0,test=testdat0),
dat1=list(model=model1,test=testdat1),
dat2=list(model=model2,test=testdat2))

#sapply over list, automatically converts to matrix
res <- sapply(data,function(dat) predict(dat\$model,newdata=dat\$test) )

> res
dat0   dat1   dat2
21.02061 24.40383 18.13825

``````

1

``````res = NULL
for (i in 1:3) {
res = rbind(res, c(i-1, predict(eval(as.name(paste0('model',i-1)))), newdata = eval(as.name(paste0('testdat',i-1)))))
}
``````