【问题标题】:r create function from lm coefficientsr 从 lm 系数创建函数
【发布时间】:2020-03-06 08:37:46
【问题描述】:

下面的代码显示了问题。我在 data.frame df 上运行了四次多项式回归 lm 以获得 model4。 然后我创建了回归函数fhat4。这按预期工作。

我想将其推广到任何多项式。所以,我使用poly 来创建modeln。这匹配model4。但我无法创建适当的函数fhatn。也许这与 for 循环有关?

df <- structure(list(x = c(0.3543937637005, 0.674911001464352, 0.21966037643142, 
0.14723521983251, 0.36166316177696, 0.975983075099066, 0.539355604210868, 
0.294046462047845, 0.853777077747509, 0.634912414476275), y = c(0.0120776002295315, 
0.655085238162428, 0.310665819328278, 0.525274415733293, 0.938241509487852, 
0.520828885724768, 0.241615766659379, 0.724816955626011, 0.808277940144762, 
0.358921303786337)), .Names = c("x", "y"), row.names = c(NA, 
-10L), class = "data.frame")

############################################# 
model4 <- lm(y~x+I(x^2)+I(x^3)+I(x^4), data=df)

fhat4 <- function (x) {
  model4$coefficients[1]+
  model4$coefficients[2]*x+
  model4$coefficients[3]*x^2+
  model4$coefficients[4]*x^3+
  model4$coefficients[5]*x^4
  }

fhat4(2)

############################################# 
modeln <- lm(y~poly(x,4,raw=TRUE), data=df)

fhatn <- function (x) {
  fn <- 0
  for (i in 0:5){
    fn <- fn + modeln$coefficients[i+1]*x^i
  }
}

fhatn(4)

【问题讨论】:

  • 函数predict.lm不提供这样的功能吗?

标签: r for-loop regression lm


【解决方案1】:

您的 for 循环应该只从 0 到 4 而不是直到 5。此外,您的函数不会返回任何内容,因此您可以在末尾添加 return(fn)

不管怎样,你可以实现相同的功能而无需任何循环:

modeln <- lm(y ~ poly(x, 4, raw = TRUE), data = df)

fhatn <- function (x) {
  sum(x^(seq_along(coef(modeln)) - 1) * coef(modeln))
}

fhatn(2)
[1] -150.6643

请注意,coef(modeln)modeln$coefficients 的替代品。

或者正如文森特在 cmets 中所说,您可以使用 predict 函数:

predict(modeln, newdata = data.frame(x = 2))
-150.6643 

【讨论】:

  • 关键是缺少回报(fn)。非常感谢。您当然是对的,i 只需要最多 4 个。由于这是一个错字,因此可以从原始问题中编辑该位。
  • 请注意,没有任何返回值的函数仍会返回某些内容,但不会在控制台中打印出某些内容。您可以尝试 print(fhatn(2)) 为您的旧功能 fhatn ,它也应该工作。还要检查this question
  • coef(fm)fm$coefficients 并不总是等价的。一般来说,应该使用coef(fm)
  • @G.Grothendieck 很高兴知道,谢谢。你能详细说明一下还是你知道一个好的来源?
  • 看源码。您可以看到它在某些情况下确实给出了与fm$coefficients 相同的结果,而在其他情况下则没有。同样fm$coefficients 取决于lm 在内部使用的特定数据结构,而如果将来发生变化,那么coef 可能会以相应的方式发生变化,但fm$coefficients 可能会中断。另请参阅:en.wikipedia.org/wiki/Information_hiding
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-21
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多