The Art of R Programming

(WallPaper) #1
if (npr > 0)
for (i in 1:npr) {
...
}
}

This loop iterates until the end of the input file is reached. The latter
condition will be sensed by encountering a zero-length Household record,
as seen in the preceding code.
Within therepeatloop, we alternate reading a Household record and
reading the associated Person records. The number of Person records for
the current Household record is extracted from columns 106 and 107 of
that record, storing this number innpr. That extraction is done by a call to
our functionintextract().
Theforloop then reads in the Person records one by one, in each case
forming the desired row for the output data frame and then attaching it to
the latter viarbind():

for (i in 1:npr) {
prec <- readLines(con,1) # get Person record
# make this person's row for the data frame
person <- makerow(serno,prec,flds)
# add it to the data frame
dtf <- rbind(dtf,person)
}

Note howmakerow()creates the row to be added for a given person. Here
the formal arguments aresrnfor the household serial number,prfor the
given Person record, andflfor the list of variable names and column fields.

makerow <- function(srn,pr,fl) {
l <- list()
l[["serno"]] <- srn
for (nm in names(fl)) {
l[[nm]] <- intextract(pr,fl[[nm]])
}
return(l)
}

For instance, consider our sample call:

pumsdf <- extractpums("pumsa",list(Gender=c(23,23),Age=c(25,26)))

Whenmakerow()executes,flwill be a list with two elements, namedGender
andAge. The stringpr, the current Person record, will haveGenderin column
23 andAgein columns 25 and 26. We callintextract()to pull out the desired
numbers.

242 Chapter 10

Free download pdf