您看到的错误消息“Function '[' is not in the derived 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 也无能为力。
我最近对Function for derivatives of polynomials of arbitrary order (symbolic method preferred) 的回答解决了您的问题。我的三个答案中提供了三种方法,都不是基于数值导数的。我个人更喜欢the one using outer(LaTeX 数学公式的唯一答案),至于多项式,一切都是精确的。
要使用该解决方案,请在此处使用函数g,并通过要评估导数的值(例如0:10)指定参数x,并通过多项式回归系数s指定pc .默认情况下,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 更简洁,如果你想要交互,它会更容易,比如How to write interactions in regressions in R?