簡體   English   中英

r 從 lm 系數創建 function

[英]r create function from lm coefficients

下面的代碼顯示了問題。 我在 data.frame df上運行四次多項式回歸lm以獲得model4 然后我創建了回歸 function fhat4 這按預期工作。

我想將其推廣到任何程度的多項式。 所以,我使用poly來創建modeln 這匹配model4 但我無法創建合適的 function 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)

您的for循環應該只有 go 從 0 到 4 直到 5。此外,您的 function 不會返回任何內容,因此您可以在最后添加return(fn)

無論如何,您可以在沒有任何循環的情況下實現相同的 function:

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

或者正如文森特在評論中所說,您可以使用預測 function:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM