Calculate the derivative of a data-function in r

R_User picture R_User · Jun 18, 2012 · Viewed 16.9k times · Source

Is there an easy way to calculate the derivative of non-liner functions that are give by data?

for example:

x = 1 / c(1000:1)

y = x^-1.5
ycs = cumsum(y)

plot (x, ycs, log="xy")

How can I calculate the derivative function from the function given by ´x´ and ´ycs´?

Answer

Marc in the box picture Marc in the box · Jun 18, 2012

Was also going to suggest an example of a smoothed spline fit followed by prediction of the derivative. In this case, the results are very similar to the diff calculation described by @dbaupp:

spl <- smooth.spline(x, y=ycs)
pred <- predict(spl)

plot (x, ycs, log="xy")
lines(pred, col=2)

ycs.prime <- diff(ycs)/diff(x)
pred.prime <- predict(spl, deriv=1)

plot(ycs.prime)
lines(pred.prime$y, col=2)