[R] how to get higher derivatives with "deriv"
peter dalgaard
pdalgd at gmail.com
Fri Jul 30 15:52:19 CEST 2010
On Jul 29, 2010, at 11:27 PM, Wu Gong wrote:
>
> ## specify the function string
> f.str <- "x^alpha"
>
> ## higher derivatives
> DD <- function(f.str, x = 2, alpha=3,order = 1){
> expr.s <- parse(text=f.str)
> while(order>=1) {
> expr.s <- D(expr.s,"x")
> order <- order-1}
> eval(expr.s)
> }
>
> compute
> DD(f.str,x=1,alpha=0.5,order=1)
>
Somewhat more elegant things can be done, consider for instance
> f
function (x,alpha) x^alpha
> ddf <- f
> body(ddf) <- D(D(body(f),"x"),"x")
> ddf
function (x, alpha)
x^((alpha - 1) - 1) * (alpha - 1) * alpha
> ddf(1,.5)
[1] -0.25
(wrapping this as a function which accepts an order argument is left as an exercise, because I'm too lazy....)
--
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list