The Art of R Programming

(WallPaper) #1
9 # if A or B already chosen, no need to look at the other comms.
10 if (commdata$numabchosen > 0) next
11 # choose committee 2 and check
12 commdata <- choosecomm(commdata,4)
13 if (commdata$numabchosen > 0) next
14 # choose committee 3 and check
15 commdata <- choosecomm(commdata,3)
16 }
17 print(commdata$countabsamecomm/nreps)
18 }
19
20 choosecomm <- function(comdat,comsize) {
21 # choose committee
22 committee <- sample(comdat$whosleft,comsize)
23 # count how many of A and B were chosen
24 comdat$numabchosen <- length(intersect(1:2,committee))
25 if (comdat$numabchosen == 2)
26 comdat$countabsamecomm <- comdat$countabsamecomm + 1
27 # delete chosen committee from the set of people we now have to choose from
28 comdat$whosleft <- setdiff(comdat$whosleft,committee)
29 return(comdat)
30 }

We number the potential committee members from 1 to 20, with per-
sons A and B having ID 1 and 2. Recalling that R lists are often used to store
several related variables in one basket, we se up a listcomdat. Its components
include the following:


  • comdat$whosleft: We simulate the random selection of the committees by
    randomly choosing from this vector. Each time we choose a committee,
    we remove the committee members’ IDs. It is initialized to 1:20, indicat-
    ing that no one has been selected yet.

  • comdat$numabchosen: This is a count of how many among the people A and
    B have been chosen so far. If we choose a committee and find this to be
    positive, we can skip choosing the remaining committees for the follow-
    ing reason: If this number is 2, we know definitely that A and B are on
    the same committee; if it is 1, we know definitely that A and B arenot
    on the same committee.

  • comdat$countabsamecomm: Here, we store a count of the number of times A
    and B are on the same committee.


Since committee selection involves subsets, it’s not surprising that a cou-
ple of R’s set operations—intersect()andsetdiff()—come in handy here.
Note, too, the use of R’snextstatement, which tells R to skip the rest of this
iteration of the loop.

206 Chapter 8

Free download pdf