创建线性回归模型时出现错误的循环中。

huangapple go评论59阅读模式
英文:

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(&quot;Sepal.Length&quot;, &quot;Sepal.Width&quot;)
for (v in di){
   model = lm (formula(paste(v, &quot; ~ Petal.Length + Petal.Width&quot;)), data = iris)
   modname = paste0(&quot;model_&quot;, 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 &lt;- lapply (setNames(di, di), function(v) {
   lm (formula(paste(v, &quot; ~ Petal.Length + Petal.Width&quot;)), data = iris)
})
answer

huangapple
  • 本文由 发表于 2023年5月11日 05:14:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定