The Art of R Programming

(WallPaper) #1
14 print(commdata$countabsamecomm/nreps)
15 }

Because this simple example has just two levels, it’s not too bad. How-
ever, nestedifstatements can become confusing when you have more levels.
Theforconstruct works on any vector, regardless of mode. You can loop
over a vector of filenames, for instance. Say we have a file namedfile1with
the following contents:

1 2 3 4 5 6

We also have a file namedfile2with these contents:

5
12
13

The following loop reads and prints each of these files. We use thescan()
function here to read in a file of numbers and store those values in a vector.
We’ll talk more aboutscan()in Chapter 10.

> for (fn in c("file1","file2")) print(scan(fn))
Read 6 items
[1]123456
Read 3 items
[1] 51213

So,fnis first set tofile1, and the file of that name is read in and printed
out. Then the same thing happens forfile2.

7.1.2 Looping Over Nonvector Sets....................................


R does not directly support iteration over nonvector sets, but there are a
couple of indirect yet easy ways to accomplish it:


  • Uselapply(), assuming that the iterations of the loop are independent
    of each other, thus allowing them to be performed in any order.

  • Useget(). As its name implies, this function takes as an argument a
    character string representing the name of some object and returns
    the object of that name. It sounds simple, butget()is a very powerful
    function.


142 Chapter 7

Free download pdf