# NOT RUN {
# }
# NOT RUN {
f <- function(x) x^2
# }
# NOT RUN {
Deriv(f)
# }
# NOT RUN {
# function (x)
# 2 * x
# }
# NOT RUN {
f <- function(x, y) sin(x) * cos(y)
# }
# NOT RUN {
Deriv(f)
# }
# NOT RUN {
# function (x, y)
# c(x = cos(x) * cos(y), y = -(sin(x) * sin(y)))
# }
# NOT RUN {
f_ <- Deriv(f)
# }
# NOT RUN {
f_(3, 4)
# }
# NOT RUN {
# x y
# [1,] 0.6471023 0.1068000
# }
# NOT RUN {
Deriv(~ f(x, y^2), "y")
# }
# NOT RUN {
# -(2 * (y * sin(x) * sin(y^2)))
# }
# NOT RUN {
Deriv(quote(f(x, y^2)), c("x", "y"), cache.exp=FALSE)
# }
# NOT RUN {
# c(x = cos(x) * cos(y^2), y = -(2 * (y * sin(x) * sin(y^2))))
# }
# NOT RUN {
Deriv(expression(sin(x^2) * y), "x")
# }
# NOT RUN {
# expression(2*(x*y*cos(x^2)))
Deriv("sin(x^2) * y", "x") # differentiate only by x
"2 * (x * y * cos(x^2))"
Deriv("sin(x^2) * y", cache.exp=FALSE) # differentiate by all variables (here by x and y)
"c(x = 2 * (x * y * cos(x^2)), y = sin(x^2))"
# Compound function example (here abs(x) smoothed near 0)
fc <- function(x, h=0.1) if (abs(x) < h) 0.5*h*(x/h)**2 else abs(x)-0.5*h
Deriv("fc(x)", "x", cache.exp=FALSE)
"if (abs(x) < h) x/h else sign(x)"
# Example of a first argument that cannot be evaluated in the current environment:
# }
# NOT RUN {
suppressWarnings(rm("xx", "yy"))
Deriv(xx^2+yy^2)
# }
# NOT RUN {
# c(xx = 2 * xx, yy = 2 * yy)
# Automatic differentiation (AD), note intermediate variable 'd' assignment
# }
# NOT RUN {
Deriv(~{d <- ((x-m)/s)^2; exp(-0.5*d)}, "x", cache.exp=FALSE)
# }
# NOT RUN {
#{
# d <- ((x - m)/s)^2
# .d_x <- 2 * ((x - m)/s^2)
# -(0.5 * (.d_x * exp(-(0.5 * d))))
#}
# Custom derivation rule
# }
# NOT RUN {
myfun <- function(x, y=TRUE) NULL # do something useful
dmyfun <- function(x, y=TRUE) NULL # myfun derivative by x.
drule[["myfun"]] <- alist(x=dmyfun(x, y), y=NULL) # y is just a logical
Deriv(myfun(z^2, FALSE), "z")
# 2 * (z * dmyfun(z^2, FALSE))
# }
# NOT RUN {
# Differentiation by list components
# }
# NOT RUN {
theta <- list(m=0.1, sd=2.)
x <- names(theta)
names(x)=rep("theta", length(theta))
Deriv(~exp(-(x-theta$m)**2/(2*theta$sd)), x, cache.exp=FALSE)
# c(theta_m = exp(-((x - theta$m)^2/(2 * theta$sd))) *
# (x - theta$m)/theta$sd, theta_sd = 2 * (exp(-((x - theta$m)^2/
# (2 * theta$sd))) * (x - theta$m)^2/(2 * theta$sd)^2))
# }
# NOT RUN {
# Differentiation in matrix calculus
# }
# NOT RUN {
Deriv(~solve(matrix(c(1, x, x**2, x**3), nrow=2, ncol=2)))
# }
Run the code above in your browser using DataCamp Workspace