Search code examples
rsymbolic-mathderivative

How can I compute partial derivatives of a function depending on multiple parameters using "Deriv"


I am trying to use the package Deriv, to compute symbolic derivatives of a function depending on one or two variables and a vector of parameters. However, i always obtain the error:

Error in FUN(X[[i]], ...) : Could not retrieve body of '[()'

I have tried:

test_fun <- function(x,y,par){x\*par[1]+y\*par[2]}  
Deriv(test_fun,"x",par=c(2,2))  

which yields the above error. So does

par <- c(2,2)  
test_fun <- function(x,y,par){x\*par[1]+y\*par[2]}  
Deriv(test_fun,"x")  

Obviously

test_fun <- function(x,y,par){x\*2+y\*2}  
Deriv(test_fun,"x")  

works as intended, but is not what I want.

Reading the Documentation for the Deriv-package, it seems that directly passing additional arguments to the function is not supported. Is there any other way to achieve the desired result?


Solution

  • Updated answer (9/16):

    There's two options below for passing the parameters through Deriv. Also note that Derive will retain curly braces in the original function, so either define your functions without them or call eval() afterwards.

    Option 1. Define within the call to Deriv

    test_fun <- function(x,y,par){x*par[1]+y*par[2]}
    eval(Deriv(test_fun(par=c(2,2)),'x'))
    # [1] 2
    

    Option 2. Define the parameter values in as a function.

    test_fun <- function(x,y,par){x*par[1]+y*par[2]}
    tpar <- function() c(2,2)
    eval(Deriv(test_fun(par=tpar()), "x"))
    # [1] 2