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

问题描述 投票:0回答:2

我想用不同的模型调用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

我想到这样做的另一种方法是将模型和testdata放在2个单独的list()中并使用for循环来调用它们,但这也没有用。还有其他方法可以做到这一点,还是我做错了什么.. TIA

r
2个回答
2
投票

我使用list和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 


1
投票

要使for循环工作,您可以进行以下更改:

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)))))
}
© www.soinside.com 2019 - 2024. All rights reserved.