I'm writing some code to calculate derivatives of functions. I managed to generate 1st and 2nd derivatives for 1 variable and store in the environment as functions, so I can plot them later. Now I'm trying to calculate the partial derivates for equations with 2 or more variables and I can't find the code that can generate as much functions in the environment as partial derivatives of the function.
To clarify, for 1 variable I used:
f <- function(x) cos(20*x)*exp(-1*x)
F.<- function (x) eval(D(as.expression(body(f)), "x"))
F..<- function (x) eval(D(as.expression(D(as.expression(body(f)), "x")),"x"))
and it worked perfect, I get the 3 functions in the environment:
But for more than 1 variable I have to loop through this functions and generate as many funtions as partial derivatives of the equation.
My question is: how can I generate a loop that calculates the partial derivatives of a function and stores them as functions, each one with a custom name?
I tried the derivative function inside a for loop but couldn't manage to define different names for each calculation of the derivatives:
for (i in 1:nro_variables) {
var_D = vector_variables[i]
F.<- function (x) eval(D(as.expression(body(f)), var_D))
}