tzu tzu - 1 month ago 9
R Question

How to Automatically Change a Local Variable within a Function in R?

To simplify the question, I will use a toy example here. I want to derive the gradient and Hessian of a polynomial function such as
library(pracma)

dummy <- function(x) {
z <- x[1]; y <- x[2]
rez <- (z^2)*(y^3)+3
rez
}
grad(dummy, c(1,2))

hessian(dummy, c(1,2))


M question is that is there an efficient way so I can derive the gradient and Hessian from different constant terms in
dummy
? e.g., the gradients and Hessians from
(z^2)*(y^3)+a
at
z=1
and
y=2
, where
a=[0.01,3]
.

Thanks!

Answer

Both pracma::hessian and pracma::grad take ... as "variables to be passed to f". If you want a to be a variable, you just need your dummy function to take it as an argument:

dummy <- function(x, a) {
         z <- x[1]; y <- x[2]
         rez <- (z^2)*(y^3)+a
         rez
         }

grad(dummy, c(1,2), a = 0.01)
# [1] 16 12
hessian(dummy, c(1,2), a = 3)
#      [,1] [,2]
# [1,]   16   24
# [2,]   24   12

sapply(seq(0.01, 3, length.out = 10), function(a) grad(dummy, c(1, 2), a = a))
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]   16   16   16   16   16   16   16   16   16    16
# [2,]   12   12   12   12   12   12   12   12   12    12

Of course the results are all the same, you are changing a constant term and then taking derivatives; the derivative of any constant is 0. But the idea will generalize to more interesting cases.

Comments