R 使用'D'获取回归多项式的导数时出错

R 使用'D'获取回归多项式的导数时出错,r,regression,linear-regression,lm,polynomials,R,Regression,Linear Regression,Lm,Polynomials,我在2D图形上有点。我想找到最适合这个模型的第三多项式,并得到它的一阶导数。但是我不能让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 polynomia

我在2D图形上有点。我想找到最适合这个模型的第三多项式,并得到它的一阶导数。但是我不能让
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")
a您看到的错误消息“函数”
[
”不在导数表中,因为
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中的一个函数(读取
?提取
?“[”

要证明类似的行为,请考虑:

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


其他备注:建议您使用
poly(a,degree=3,raw=TRUE)
而不是
I()
。他们在这里也这么做,但是
poly
更简洁,如果您想要交互,就更容易了,就像在中一样,很好,thx,但是我如何绘制派生呢?
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