R can't fit a quadratic equation by resulting an error: subscript out of bounds

R can't fit a quadratic equation by resulting an error: subscript out of bounds

我有一个简单的数据集:

x <- c(1.053848,1.054189,1.054529)
y <- c(0.0137554979,0.0006841939,0.0007282808)

让抛物线拟合 y

ypoly <- lm(y ~ x + I(x^2))

我想得到公式中的常量a

y = ax^2 + bx + c

所以我输入 summary(ypoly)$coefficients[3, 1] 并收到此错误:

Error in summary(ypoly)$coefficients[3, 1] : subscript out of bounds

因为

Coefficients:
(Intercept)           x         I(x^2)  
      25.17       -19.13           NA 

Check this fitting output on Wolfram Alpha

问题出在哪里?

如果您查看此线性回归的设计矩阵,R 会告诉您它在计算上是奇异的,这意味着它没有逆矩阵。 OLS 的封闭形式表达式是 ,但您无法计算此数据的倒数。你可以看到这个,

x <- c(1.053848,1.054189,1.054529)
y <- c(0.0137554979,0.0006841939,0.0007282808)
x2 <- x^2
design <- matrix(c(rep(1, 3), x, x2), ncol = 3)
solve(t(design)%*%design)

我假设你的问题是你的 x 值和 x^2 值有多接近。要解决这个问题,您可以 运行 这个代替。

ypoly <- lm(y ~ poly(x, 2))

希望对您有所帮助!