Use Built-in Math Functions

When possible, try to use built-in functions for mathematical computations instead of writing R code to perform those computations. Many common math functions are included as native functions in R. In most cases, these functions are implemented as calls to external math libraries. As an obvious example, if you want to multiply two matrices together, you should probably use the %∗% operator and not write your own matrix multiplication code in R.

Often, it is possible to use built-in functions by transforming a problem. As an example, let’s consider an example from queueing theory. Queueing theory is the study of systems where “customers” arrive, wait in a “queue” for service, are served, and then leave. As an example, picture a cafeteria with a single cashier. After customers select their food, they proceed to the cashier for payment. If there is no line, they pay the cashier and then leave. If there is a line, they wait in the line until the cashier is free. If we suppose that customers arrive according to a Poisson process and that the time required for the cashier to finish each transaction is given by an exponential distribution, then this is called an M/M/1 queue. (This means “memoryless” arrivals, “memoryless” service time, and one server.)

A very useful formula for queueing theory is Erlang’s B formula. Picture a call center with n operators but no queue: if a customer calls the center and there is a free operator, then the operator will answer the ...

Get R in a Nutshell 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.