我在二维图上有点。我想找到最适合这个模型的第三次多项式,并得到它的一阶导数。但是我不能让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")
D中的错误(表达式(s1+ s2 *a+ (a^2) * s3 + (a^3) * s4),: 函数'
[
‘不在导数表中
我想避免通过差分来计算数值导数。谢谢你帮忙!
发布于 2016-11-05 23:07:37
您看到的“'**[
**‘函数不在派生表”中的错误消息是因为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中的一个函数(read ?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)的回答解决了。在我的三个答案中提供了三种方法,没有一种是基于数值导数的。我个人更喜欢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?中一样
https://stackoverflow.com/questions/34799673
复制相似问题