使用“D”获取我的回归多项式的导数时出错

Error when using `D` to get derivative of my regression polynomial

我在二维图形上有点。我想找到适合该模型的最佳三阶多项式并获得其一阶导数。但是我无法使 D 函数正常工作。这是一个简单的例子:

a <- 0:10
b <- c(2, 4, 5, 8, 9, 12, 15, 16, 18, 19, 20)
plot(a, b)
m1 <- lm(b ~ a + I(a ^ 2) + I(a ^ 3))
s <- coef(m1)

## try to get 1st derivative of the regression polynomial
D(expression(s[1] + s[2] * a + (a ^ 2) * s[3] + (a ^ 3) * s[4]), "a")

Error in D(expression(s[1] + s[2] * a + (a^2) * s[3] + (a^3) * s[4]), :

Function '[' is not in the derivatives table

我想避免通过差分计算数值导数。感谢您的帮助!

你看到的错误信息“Function '[' is not in the derivatives table”是因为D只能识别一组用于符号操作的函数。您可以在 ?D:

中找到它们
The internal code knows about the arithmetic operators ‘+’, ‘-’,
‘*’, ‘/’ and ‘^’, and the single-variable functions ‘exp’, ‘log’,
‘sin’, ‘cos’, ‘tan’, ‘sinh’, ‘cosh’, ‘sqrt’, ‘pnorm’, ‘dnorm’,
‘asin’, ‘acos’, ‘atan’, ‘gamma’, ‘lgamma’, ‘digamma’ and
‘trigamma’, as well as ‘psigamma’ for one or two arguments (but
derivative only with respect to the first).  (Note that only the
standard normal distribution is considered.)

虽然 "[" 实际上是 R 中的一个函数(阅读 ?Extract?"[")。

要演示类似的行为,请考虑:

s <- function (x) x

D(expression(s(x) + x ^ 2), name = "x")
# Error in D(expression(s(x) + x^2), name = "x") : 
#  Function 's' is not in the derivatives table

在这里,即使s被定义为一个简单的函数,D也不能用它做任何事情。

我最近对 ​​. Three methods are provided in three of my answers, none of which are based on numerical derivatives. I personally prefer to 的回答(LaTeX 数学公式的唯一答案)解决了你的问题,至于多项式,一切都是准确的。

要使用该解决方案,请在此处使用函数 g,并通过要计算导数的值(例如 0:10)和 [=25] 指定参数 x =] 通过你的多项式回归系数 s。默认情况下,nderiv = 0L 因此返回多项式本身,就像调用 predict.lm(m1, newdata = list(a = 0:10)) 一样。但是一旦指定了 nderiv,您就会得到回归曲线的精确导数。

a <- 0:10
b <- c(2, 4, 5, 8, 9, 12, 15, 16, 18, 19, 20)
plot(a, b)
m1 <- lm(b ~ a + I(a ^ 2) + I(a ^ 3))
s <- coef(m1)
#(Intercept)           a      I(a^2)      I(a^3) 
# 2.16083916  1.17055167  0.26223776 -0.02020202 

## first derivative at your data points
g(0:10, s, nderiv = 1)
# [1] 1.1705517 1.6344211 1.9770785 2.1985237 2.2987568 2.2777778 2.1355866
# [8] 1.8721834 1.4875680 0.9817405 0.3547009

其他备注:建议您使用poly(a, degree = 3, raw = TRUE)而不是I()。他们在这里做同样的事情,但是 poly 更简洁,如果你想要交互,它会更容易,比如