如何在 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 的多项式并使用它来求解或预测?
我需要解方程,这意味着用函数 得到 x 给定的 ay base::solve
。
谢谢