问题描述
如何提取R中正交多项式回归的系数?
它像带有原始回归的魅力一样工作:
#create datas
set.seed(120)
x= 1:20
y=x^2 + rnorm(length(x),10)
datas = data.frame(x,y)
#compute raw model with function poly
mod= lm(data=datas,y~poly(x,2,raw=T))
#get coefficients with function coef()
coefficients = coef(mod)
#construct polynom and check fitted values
fitted_values = mod$fitted.values
x0 = datas$x[1]
solution = coefficients[1]+ coefficients[2]*x0^1 + coefficients[3]*x0^2
print(solution)
# 1.001596
print(fitted_values[1])
# 1.001596
# 1.001596 == 1.001596
但是在正交lm上用函数coef
获得的系数不起作用:
#create datas
set.seed(120)
x= 1:20
y=x^2 + rnorm(length(x),y)
#compute raw model with function poly
mod = lm(data=datas,raw=F))
#get coefficients with function coef()
coefficients = coef(mod)
fitted_values = mod$fitted.values
#construct polynom and check fitted values
x0 = datas$x[1]
solution = coefficients[1]+ coefficients[2]*x0^1 + coefficients[3]*x0^2
print(solution)
# 805.8476
print(fitted_values[1])
# 1.001596
# 1.001596 != 805.8476
是否还有另一种方法来获取正确的参数,以构造形式为c0 + c1 * x + .. + cn * x ^ n的多项式并用其求解或预测?
我需要求解方程,这意味着使用函数 base::solve
将x赋予y。
谢谢
解决方法
问题是您不仅需要系数,而且还需要正交多项式(而不是您要使用的原始多项式)。后者由model.matrix
构造:
newdata <- model.matrix(~ poly(x,2),data = datas)
solution <- newdata %*% coefficients
print(solution[1])
# [1] 1.001596
print(fitted_values[1])
#1.001596
我不了解与solve
的连接,但是相信您可以从这里获取。