Skip to content

First Derivative of Data Matrix

4 messages · thaumaturgy, David Winsemius, Spencer Graves

#
I am really new to R and ran across a need to take a data matrix and
calculate an approximation of the first derivative of the data.  I am more
than happy to do an "Excel" kind of calculation (deltaY/deltaX) for each
pair of rows down the matrix, but I don't know how to get R to do that kind
of calculation.  I'd like to store it as a 3rd column in the matrix as well.

My data looks like this:
     acflong
1  1.0000000
2  0.9875858
3  0.9871751
4  0.9867585
5  0.9863358
6  0.9859070
7  0.9854721
8  0.9850316
9  0.9817161
10 0.9812650

and I'd like to generate a table like this:

     acflong          dacflong/dx
1  1.0000000
2  0.9875858        -0.01241          #delta(acflong)/delta(index)
3  0.9871751        -0.00041
4  0.9867585        -0.00042
5  0.9863358        -0.00042
6  0.9859070        -0.00043
7  0.9854721        -0.00043
8  0.9850316        -0.00044
9  0.9817161        -0.00033
10 0.9812650       -0.00045

Is there a way to do this in R and how do I eliminate the first line of the
data?

Thanks,
-Chris
#
delta(index) is identically 1, so taking first differences is all that  
is needed. If the dtatframe's name is df then:

df$dacflong_dx <- c(NA, diff(acflong))     # the slash would not be a  
legal character in a variable name unless you jumped through some  
hoops that appear entirely without value

If you want to get rid of the first line of df then

df[-1]
#
However, estimating derivatives from differencing data amplifies 
minor errors.  Less noisy estimates can be obtained by first smoothing 
and then differentiating the smooth.  The "fda" package provides 
substantial facilities for this. 

      Hope this helps. 
      Spencer Graves
David Winsemius wrote: