r - 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
解决方案
我使用列表来解决您的问题,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
推荐阅读
- docker - docker 在 Windows 10 中显示权限提升错误
- c++ - 不能在类中创建多个对象
- math - 数学问题:考虑支付处理器费用计算要支付的价格
- python-3.x - 使用 train_test_split 并使用 mne CSP 进行交叉验证的不同结果
- c# - C# 将分钟添加到计时器 (WPF/XAML)
- c++ - 如何在 c++ 中使用不同长度的数组初始化嵌套的 2D int 数组(或指向 int[] 的指针数组?)?
- django-models - 模型指的是同一models.py中的另一个类
- reactjs - React Draft WYSIWYG - 将数据包装在 div 或 span 中
- ios - 致命异常: NSInternalInconsistencyException ,在计算索引路径处插入行的新间隙的开始时,先前的新全局行无效
- python - 如何在python中从数据集中选择行