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

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

Error creating linear regression model in for loop

问题

以下是翻译好的部分:

我正在创建一些对象,每个对象都是一个lm模型。
这是一个使用iris的示例:

  1. di = c("Sepal.Length", "Sepal.Width")
  2. for (v in di){
  3. model = lm (v ~ Petal.Length + Petal.Width, data = iris)
  4. modname = paste0("model_", v)
  5. assign(modname, model)
  6. }

这给我带来了错误:

  1. Error in model.frame.default(formula = v ~ Petal.Length + Petal.Width, :
  2. 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:

  1. di = c("Sepal.Length", "Sepal.Width")
  2. for (v in di){
  3. model = lm (v ~ Petal.Length + Petal.Width, data = iris)
  4. modname = paste0("model_", v)
  5. assign(modname, model)
  6. }

This gives me the error:

  1. Error in model.frame.default(formula = v ~ Petal.Length + Petal.Width, :
  2. 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()函数。

  1. di = c("Sepal.Length", "Sepal.Width")
  2. for (v in di){
  3. model = lm (formula(paste(v, " ~ Petal.Length + Petal.Width")), data = iris)
  4. modname = paste0("model_", v)
  5. assign(modname, model)
  6. }

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()函数修改全局环境是不良实践。尝试将模型追加到一个列表中,这样所有模型都会被组合在一个数据结构中。

  1. answer <- lapply(setNames(di, di), function(v) {
  2. lm (formula(paste(v, " ~ Petal.Length + Petal.Width")), data = iris)
  3. })
  4. answer
英文:

In your expression v is just a string. You need to convert it to a formula. See the formula() function.

  1. di = c(&quot;Sepal.Length&quot;, &quot;Sepal.Width&quot;)
  2. for (v in di){
  3. model = lm (formula(paste(v, &quot; ~ Petal.Length + Petal.Width&quot;)), data = iris)
  4. modname = paste0(&quot;model_&quot;, v)
  5. assign(modname, model)
  6. }

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:

  1. answer &lt;- lapply (setNames(di, di), function(v) {
  2. lm (formula(paste(v, &quot; ~ Petal.Length + Petal.Width&quot;)), data = iris)
  3. })
  4. 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:

确定