In base R, there is a function “deriv” from stats library to compute derivatives of simple expressions, symbolically and algorithmically. Here I use another function “Deriv” from Deriv library.
To calculate both gradient and hessian matrix of a two-variable function:
library(Deriv)
f <- function(x, y) x * sin(y) + 1
derivatives <- Deriv(f, nderiv = c(1,2))
Then evaluate the value at point (2, 0) :
x <- c(2,0)
derivatives(x[1], x[2])
# output
$`1`
x y
0 2
$`2`
x.x x.y y.x y.y
0 1 1 0
To calculate the directional derivative of a function f (x) = x1*x2 at x = [1, 0] in
the direction s = [−1,−1], the formula is:

And the implementation in R is:
f <- function(x, y) x*y
x <- c(1, 0)
s <- c(-1, -1)
gradient <- Deriv(f)
directionalDeriv <- sum(gradient(x[1], x[2]) * s)