Search code examples
rderivative

get a derivative by knowing two numeric vectors


I know two vectors x and y, how can I calculate derivatives of y with respect to x in R ?

x<-rnorm(1000)
y<-x^2+x

I want to caculate derivative of y with respect to x: dy/dx; suppose I don't know the underlying function between x and y. There can be a value in derivative scale corresponding to each x.


Solution

  • To find the derivative use the numeric approximation: (y2-y1)/(x2-x1) or dy/dx. In R use the diff function to calculate the difference between 2 consecutive points:

    x<-rnorm(100)
    y<-x^2+x
    
    #find the average x between 2 points
    avex<-x[-1]-diff(x)/2
    #find the numerical approximation
    #delta-y/delta-x
    dydx<-diff(y)/diff(x)
    
    #plot numeric approxiamtion
    plot(x=avex, dydx)
    #plot analytical answer
    lines(x=avex, y=2*avex+1)