Vectorized Operations
Suppose we have a function f()
that we wish to apply to all elements of a vector x
. In many cases, we can accomplish this by simply calling f()
on x
itself. This can really simplify our code and, moreover, give us a dramatic performance increase of hundredsfold or more.
One of the most effective ways to achieve speed in R code is to use operations that are vectorized, meaning that a function applied to a vector is actually applied individually to each element.
Vector In, Vector Out
You saw examples of vectorized functions earlier in the chapter, with the +
and *
operators. Another example is >
.
> u <- c(5,2,8) > v <- c(1,3,9) > u > v [1] TRUE FALSE FALSE
Here, the >
function was applied to u[1]
and v[1]
, resulting in TRUE
Get The Art of R Programming 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.