首页 > 解决方案 > For循环调用不同的函数变量

问题描述

我想predict使用不同的模型调用该函数来提取其预测值。我尝试使用paste0来调用正确的模型,但它不起作用,例如:

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

我想到的另一种方法是将模型和测试数据分开放置,list()并使用 for 循环来调用它们,但这也不起作用。有没有其他方法可以做到这一点,或者我做错了什么.. TIA

标签: r

解决方案


我使用列表来解决您的问题,sapply因此我们不需要rbind()一遍又一遍地定义外部变量。

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 


推荐阅读