# [R] Partial Derivatives in R

David Winsemius dwinsemius at comcast.net
Sun May 10 23:06:31 CEST 2009

```On May 10, 2009, at 10:05 AM, Paul Heinrich Dietrich wrote:

>
> Quick question:
>
> Which function do you use to calculate partial derivatives from a
> model
> equation?
>
> I've looked at deriv(), but think it gives derivatives, not partial
> derivatives.

Your reading of the help page and the examples differs from mine. It
says:
" It returns a call for computing the expr and its (partial)
derivatives, simultaneously."

> dx2x <- deriv(~ x^2, "x") ; dx2x  # the example on the help page
expression({
.value <- x^2
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- 2 * x
attr(.value, "gradient") <- .grad
.value
})
> dyx2.x <- deriv(~ y*x^2, "x") ; dyx2.x
expression({
.value <- y * x^2
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- y * (2 * x)
attr(.value, "gradient") <- .grad
.value
})
> dy2x2.x <- deriv(~ y^2*x^2, "x") ; dy2x2.x
expression({
.expr1 <- y^2
.value <- .expr1 * x^2
.grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
.grad[, "x"] <- .expr1 * (2 * x)
attr(.value, "gradient") <- .grad
.value
})
> dy2x2.xy <- deriv(~ y^2*x^2, c("x","y")) ; dy2x2.xy
expression({
.expr1 <- y^2
.expr2 <- x^2
.value <- .expr1 * .expr2
.grad <- array(0, c(length(.value), 2L), list(NULL, c("x",
"y")))
.grad[, "x"] <- .expr1 * (2 * x)
.grad[, "y"] <- 2 * y * .expr2
attr(.value, "gradient") <- .grad
.value
})

> Of course my equation isn't this simple, but as an example,
> I'm looking for something that let's you control whether it's a
> partial or
> not, such as:
>
> somefunction(y~a+bx, with respect to x, partial=TRUE)
>

That appears to be precisely what your are offered with deriv, ....
just not needing the partial=TRUE

deriv(
David Winsemius, MD
Heritage Laboratories
West Hartford, CT

```

More information about the R-help mailing list