英文:
Error creating linear regression model in for loop
问题
以下是翻译好的部分:
我正在创建一些对象,每个对象都是一个lm
模型。
这是一个使用iris
的示例:
di = c("Sepal.Length", "Sepal.Width")
for (v in di){
model = lm (v ~ Petal.Length + Petal.Width, data = iris)
modname = paste0("model_", v)
assign(modname, model)
}
这给我带来了错误:
Error in model.frame.default(formula = v ~ Petal.Length + Petal.Width, :
variable lengths differ (found for 'Petal.Length')
这些模型在真实数据中,即使存在NA
值时,也能正常工作,当它们分别创建时。
英文:
I am creating a number of objects, each a lm
model
This is an example with iris
:
di = c("Sepal.Length", "Sepal.Width")
for (v in di){
model = lm (v ~ Petal.Length + Petal.Width, data = iris)
modname = paste0("model_", v)
assign(modname, model)
}
This gives me the error:
Error in model.frame.default(formula = v ~ Petal.Length + Petal.Width, :
variable lengths differ (found for 'Petal.Length')
The models work correctly, despite NA
, in the real data, when they are created separately
答案1
得分: 1
In your expression v is just a string. You need to convert it to a formula. See the formula()
function.
在你的表达式中,v只是一个字符串。你需要将它转换成一个公式。请参考formula()
函数。
di = c("Sepal.Length", "Sepal.Width")
for (v in di){
model = lm (formula(paste(v, " ~ Petal.Length + Petal.Width")), data = iris)
modname = paste0("model_", v)
assign(modname, model)
}
Word of advice it is generally a poor practice to modify the global environment using the assign()
function. Try appending the model onto a list, that way all of the models are grouped together in one data structure.
建议一句,通常使用assign()
函数修改全局环境是不良实践。尝试将模型追加到一个列表中,这样所有模型都会被组合在一个数据结构中。
answer <- lapply(setNames(di, di), function(v) {
lm (formula(paste(v, " ~ Petal.Length + Petal.Width")), data = iris)
})
answer
英文:
In your expression v is just a string. You need to convert it to a formula. See the formula()
function.
di = c("Sepal.Length", "Sepal.Width")
for (v in di){
model = lm (formula(paste(v, " ~ Petal.Length + Petal.Width")), data = iris)
modname = paste0("model_", v)
assign(modname, model)
}
Word of advice it is generally a poor practice to modify the global environment using the assign()
function. Try appending the model onto a list, that way all of the models are grouped together in one data structure.
Such as this:
answer <- lapply (setNames(di, di), function(v) {
lm (formula(paste(v, " ~ Petal.Length + Petal.Width")), data = iris)
})
answer
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论