【发布时间】: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