Calculate the derivative of a data-function in r

前端 未结 4 1696
忘了有多久
忘了有多久 2020-12-17 05:08

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 = cumsu         


        
相关标签:
4条回答
  • 2020-12-17 05:22

    There is also gradient from the pracma package.

    grad <- pracma::gradient(ycs, h1 = x)
    plot(grad, col = 1)
    
    0 讨论(0)
  • 2020-12-17 05:31

    Generating derivatives from raw data is risky unless you are very careful. Not for nothing is this process known as "error multiplier." Unless you know the noise content of your data and take some action (e.g. spline) to remove the noise prior to differentiation, you may well end up with a scary curve indeed.

    0 讨论(0)
  • 2020-12-17 05:35

    The derivative of a function is dy/dx, which can be approximated by Δy/Δx, that is, "change in y over change in x". This can be written in R as

    ycs.prime <- diff(ycs)/diff(x)
    

    and now ycs.prime contains an approximation to the derivative of the function at each x: however it is a vector of length 999, so you will need to shorten x (i.e. use x[1:999] or x[2:1000]) when doing any analysis or plotting.

    0 讨论(0)
  • 2020-12-17 05:41

    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)
    
    0 讨论(0)
提交回复
热议问题