Home > other >  Partially differentiate a function in R using the 'Deriv' package
Partially differentiate a function in R using the 'Deriv' package

Time:01-17

I need to write a function in R which depends on a vector x (which changes with every simulation) and has parameters beta_0, beta_1, beta_2. I'm trying to find the partial derivative of this function with respect to beta_0, beta_1 and beta_2. I have written a code for the same but its repeatedly returning errors.

My R code is as follows:

func_1 <- function(x,beta_0,beta_1,beta_2){
  
  k <- beta_0 (x[1]*beta_1) (x[2]*beta_2)
  k <- exp(k)/(1 exp(k))
  
}
Deriv(func_1(x=c(2,3)), 'beta_0') 

The following error is being returned:

Error in func_1(x = c(2, 3)) : 
  argument "beta_0" is missing, with no default
In addition: Warning message:
In Deriv(func_1(x = c(2, 3)), "beta_0") :
  restarting interrupted promise evaluation 

CodePudding user response:

If you want the partial derivative with respect to beta_0 you still need to specify values for all of the parameters. You also need to pass Deriv a function (or an expression); in your example you're trying to evaluate the function at x=c(2,3) (without specifying values of the other arguments/parameters). In other words, if you have a function foo you need to pass foo, not foo([something]). So for example:

library(Deriv)
dd <- Deriv(func_1, "beta_0")
dd(x=c(2,3), beta_0 = 1, beta_1 = 1, beta_2 =1)
##      beta_0 
## 0.002466509 

Here dd is the partial derivative with respect to beta_0, which is a function that can be evaluated at any numerical values you like. (if you need a symbolic partial derivative - i.e.. the value for arbitrary values of beta_0, beta_1, beta_2 - I'm not sure that Deriv will do that ...)

  •  Tags:  
  • Related