I am exploring autodiff, and I would like to use Deriv
for computing a derivative of a function wrt to a vector. I write
library(numDeriv)
library(Deriv)
h = function(x) c(1,2)%*%x
grad(h,c(1,2)) #ok
#[1] 1 2
dh=Deriv(h,x='x')
#Error in c(1, 2) %*% 1 : non-conformable arguments
dh(c(1,2))
Does anyone have a good way to do this?
From help(Deriv)
, it seems like one should be able to let the argument be a vector
here is a side effect with vector length. E.g. in Deriv(~a+bx, c("a", "b")) the result is c(a = 1, b = x). To avoid the difference in lengths of a and b components (when x is a vector), one can use an optional parameter combine Deriv(~a+bx, c("a", "b"), combine="cbind") which gives cbind(a = 1, b = x) producing a two column matrix which is probably the desired result here.
I would like to avoid making each of the vector components a different argument to the function.
For example numDeriv
above lets us easily take a derivative wrt vector x