exp(2)[1] 7.389056
Functions in R are often vectorized. For example:
exp(2)[1] 7.389056
I give it one number, and it returns one number. If instead, I supply a vector, I get this:
[1] 4.978707e-02 1.001001e+00 7.389056e+00 1.484132e+02 3.773020e+260
[6] 2.718282e+00 1.000000e+00
So when I supply a regular ol’ number as an argument, the exp function returns a number. When I supply a vector, it returns a vector; the exp function knows to act entry-wise and give me back a vector with the output of each entry-wise computation. In other words, I didn’t have to write a loop to manually do this. The function is vectorized, so it effectively runs the loop for me.
So consider for instance the set of numbers \(A = \{-100, -6, 0.001, \pi, 30\}\), and this stupid function:
\[ f(x) = \ln^2\left|\frac{2x}{1-\sin(x)}\right|. \]
If I wanted to compute the value of \(f\) for each of the arguments in \(A\), I could write a loop that goes entry-by-entry through \(A\) and applies the function \(f\) to it. But in R, because arithmetic operations are vectorized, I can do this:
[1] 36.051349 7.910714 38.608919 3.377792 11.609009
Dumb!
All of the basic arithmetic operations are vectorized like this:
c(1, 2, 3) + 2[1] 3 4 5