I need to create the Hessian matrix of a function given as:
func <- expression(sin(x+y)+cos(x-y))
vars <- c("x", "y")
I need the second order derivatives as expressions too, and I need to evaluate them lot of times, so I made a list of first order derivatives, and a list of list of second order derivatives.
funcD <- lapply(vars, function(v) D(func, v))
funcDD <- list(); for (i in 1:length(vars)) funcDD[[i]] <- lapply(vars, function(v) D(funcD[[i]], v))
So far, it works.
> funcDD
[[1]]
[[1]][[1]]
-(sin(x + y) + cos(x - y))
[[1]][[2]]
-(sin(x + y) - cos(x - y))
[[2]]
[[2]][[1]]
cos(x - y) - sin(x + y)
[[2]][[2]]
-(cos(x - y) + sin(x + y))
Now the questions: How can I create a matrix containing values of the evaluated expressions? Tried outer, didn't work.
> h <- outer(c(1:length(vars)), c(1:length(vars)), function(r, c) eval(funcDD[[r]][[c]], envir = list(x = 1, y = 2)))
Error in funcDD[[r]] : subscript out of bounds
Other question: Is there a more elegant way to store the second order derivative expressions? For instance is it possible to store expressions in a matrix instead of lists of lists?
Third question: Is it possible to get a vector of variables of an expression? Above I used vars <- c("x", "y") which I entered as input manually, is it necessary or is there a "get_variables"-like method?