【问题标题】:Error when using `D` to get derivative of my regression polynomial使用“D”获取回归多项式的导数时出错
【发布时间】:2016-01-14 21:02:24
【问题描述】:

我在 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")

D(表达式(s[1] + s[2] * a + (a^2) * s[3] + (a^3) * s[4]) 中的错误,:

函数“[”不在导数表中

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

【问题讨论】:

  • 工作正常,谢谢,但我如何绘制推导?

标签: r regression linear-regression lm polynomials


【解决方案1】:

您看到的错误消息“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?

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 2017-04-11
    • 2017-04-23
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    相关资源
    最近更新 更多