2016-09-21 20 views

回答

5

是的,有。見help("D")

DD <- function(expr, name, order = 1) { 
    if(order < 1) stop("'order' must be >= 1") 
    if(order == 1) D(expr, name) 
    else DD(D(expr, name), name, order - 1) 
} 

ddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 1)) 
dddnorm <- function(x) eval(DD(expression(dnorm(x)), "x", order = 2)) 

curve(dnorm(x), -2, 2, ylim = c(-0.4, 0.4)) 
curve(ddnorm(x), -2, 2, add = TRUE, col = "dark red") 
curve(dddnorm(x), -2, 2, add = TRUE, col = "dark blue") 

legend(x = "topleft", legend = c("dnorm", "first derivative", "second derivative"), 
     col = c("black", "dark red", "dark blue"), 
     lty = 1) 

resulting plot