The Art of R Programming

(WallPaper) #1
Notice that the modulo operator for remainder arithmetic is%%in R, as
indicated by the comment. For example, 38 divided by 7 leaves a remainder
of 3:

>38%%7
[1] 3

For instance, let’s see what happens with the following code:

for (n in x) {
if(n%%2==1)k<-k+1
}

First, it setsntox[1], and then it tests that value for being odd or even. If
the value is odd, which is the case here, the count variablekis incremented.
Thennis set tox[2], tested for being odd or even, and so on.
By the way, C/C++ programmers might be tempted to write the preced-
ing loop like this:

for (i in 1:length(x)) {
if (x[i] %% 2 == 1) k <- k+1
}

Here,length(x)is the number of elements inx. Suppose there are 25
elements. Then1:length(x)means 1:25, which in turn means 1,2,3,...,25.
This code would also work (unlessxwere to have length 0), but one of the
major themes of R programming is to avoid loops if possible; if not, keep
loops simple. Look again at our original formulation:

for (n in x) {
if(n%%2==1)k<-k+1
}

It’s simpler and cleaner, as we do not need to resort to using thelength()
function and array indexing.
At the end of the code, we use thereturnstatement:

return(k)

This has the function return the computed value ofkto the code that called
it. However, simply writing the following also works:

k

R functions will return the last value computed if there is no explicitreturn()
call. However, this approach must be used with care, as we will discuss in
Section 7.4.1.

8 Chapter 1

Free download pdf