Calculus

The rules of differentiation and integration are known to R. You will use them in modelling (e.g. in calculating starting values in non-linear regression) and for numeric minimization using optim. Read the help files for D and integrate to understand the limitations of these functions.

Derivatives

The R function for symbolic and algorithmic derivatives of simple expressions is D. Here are some simple examples to give you the idea. See also ?deriv.

D(expression(2*x^3),"x")

2 * (3 * x^2)
D(expression(log(x)),"x")

1/x

D(expression(a*exp(-b * x)),"x")

-(a * (exp(-b * x) * b))

D(expression(a/(1+b*exp(-c * x))),"x")

a * (b * (exp(-c * x) * c))/(1 + b * exp(-c * x))^2

trig.exp <-expression(sin(cos(x + y^2)))
D(trig.exp, "x")

-(cos(cos(x + y^2)) * sin(x + y^2))

Integrals

The R function is integrate. Here are some simple examples to give you the idea:

integrate(dnorm,0,Inf)

0.5 with absolute error < 4.7e-05

integrate(dnorm,-Inf,Inf)

1 with absolute error < 9.4e-05

integrate(function(x) rep(2, length(x)), 0, 1)

2 with absolute error < 2.2e-14

integrand <-function(x) {1/((x+1)*sqrt(x))}
integrate(integrand, lower = 0, upper = Inf)

3.141593 with absolute error < 2.7e-05

xv<-seq(0,10,0.1)
plot(xv,integrand(xv),type="l")

The area under the curve is π = 3.141593.

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.