【发布时间】:2020-09-21 14:21:20
【问题描述】:
如何在 R 中提取正交多项式回归的系数?
它就像一个带有原始回归的魅力:
#create datas
set.seed(120)
x= 1:20
y=x^2 + rnorm(length(x),0,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),0,10)
datas = data.frame(x,y)
#compute raw model with function poly
mod = lm(data=datas, y~poly(x,2,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。
谢谢
【问题讨论】: