r从lm系数创建函数

问题描述 投票:1回答:1

下面的代码显示了问题。我在数据框lm上进行了四次多项式回归df,以获得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)
r for-loop regression lm
1个回答
2
投票

您的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的替代。

或者正如文森特在评论中所说,您可以使用预测功能:

predict(modeln, newdata = data.frame(x = 2))
-150.6643 
© www.soinside.com 2019 - 2024. All rights reserved.