round(1.2)
[1] 1
Here, we used the built-in functionround(), but you can do the same
thing with functions that you write yourself.
As mentioned earlier, even operators such as+are really functions. For
example, consider this code:
y <- c(12,5,13)
y+4
[1] 16 9 17
The reason element-wise addition of 4 works here is that the+is actually
a function! Here it is explicitly:
'+'(y,4)
[1] 16 9 17
Note, too, that recycling played a key role here, with the 4 recycled into
(4,4,4).
Since we know that R has no scalars, let’s consider vectorized functions
that appear to have scalar arguments.
f
function(x,c) return((x+c)^2)
f(1:3,0)
[1]149
f(1:3,1)
[1] 4 9 16
In our definition off()here, we clearly intendcto be a scalar, but, of
course, it is actually a vector of length 1. Even if we use a single number for
cin our call tof(), it will be extended through recycling to a vector for our
computation ofx+cwithinf(). So in our callf(1:3,1)in the example, the
quantityx+cbecomes as follows:
⎛
⎝
1
2
3
⎞
⎠+
⎛
⎝
1
1
1
⎞
⎠
This brings up a question of code safety. There is nothing inf()that
keeps us from using an explicit vector forc, such as in this example:
f(1:3,1:3)
[1] 41636
You should work through the computation to confirm that (4,16,36) is
indeed the expected output.
Vectors 41