Search code examples
rderivative

R Function to Find Derivative of Every Point in Time Series


I have a smoothed time series and want to find the instantaneous velocity of the function at any point along the line.

What I want to do is take a series of values: ex(1,6,5,4,3,5,6,7,1) and return the derivative of each relative to the function of the entire series, such that at every point in time, I know what direction the line is trending.

I am new to R, but know there must be a way.

Any tips?

Ex:

library(smoother)
data(BJsales)
m <- data.frame(BJsales)

x.smth <- as.data.frame(smth.gaussian(m$BJsales,tails=TRUE,alpha = 5))

x.smth.ts <- cbind(seq(1:nrow(m)),x.smth)

colnames(x.smth.ts) <- c("x","y")

x.smth.ts

plot(x.smth.ts$y~x.smth.ts$x)

Desired output:

df with 2 columns: x, deriv.of.y

Edit: Final Result thanks to G5W

TS with Color by Derivative


Solution

  • Your proposed example using the BJSales data is decidedly not differentiable, BJSales

    so instead I will show the derivative of a much smoother function. If your real data is smooth, this should work for you.

    The simplest way to approximate the derivative is simply to use finite differences.
    f'(x) ≈ (f(x+h) - f(x))/h

    ## Smooth sample function
    x = seq(0,10,0.1)
    y = x/2 + sin(x)
    plot(x,y, pch=20)
    
    ## Simplest - first difference
    d1 = diff(y)/diff(x)
    d1 = c(d1[1],d1)
    

    Let's use it to plot a tangent line as an error check. I picked a place to draw the tangent line arbitrarily: the 18th point, x=1.7

    plot(x,y, type="l")
    abline(y[18]-x[18]*d1[18], d1[18]) 
    

    Tangent Line

    To get the data.frame that you requested, you just need

    Derivative = data.frame(x, d1)