Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ThinkStats in R by @hrbrmstr
- # Example 1.2
- # File format info: http://www.cdc.gov/nchs/nsfg/nsfg_cycle6.htm
- # setup a data frame that has the field start/end info
- pFields <- data.frame(name = c('caseid', 'nbrnaliv', 'babysex', 'birthwgt_lb','birthwgt_oz','prglength', 'outcome', 'birthord', 'agepreg', 'finalwgt'),
- begin = c(1, 22, 56, 57, 59, 275, 277, 278, 284, 423),
- end = c(12, 22, 56, 58, 60, 276, 277, 279, 287, 440)
- )
- # calculate widths so we can pass them to read.fwf()
- pFields$width <- pFields$end - pFields$begin + 1
- # we aren't reading every field (for the book exercises)
- pFields$skip <- (-c(pFields$begin[-1]-pFields$end[-nrow(pFields)]-1,0))
- widths <- c(t(pFields[,4:5]))
- widths <- widths[widths!=0]
- # read in the file
- pregnancies <- read.fwf("2002FemPreg.dat", widths)
- # assign column names
- names(pregnancies) <- pFields$name
- # divide mother's age by 100
- pregnancies$agepreg <- pregnancies$agepreg / 100
- # convert weight at birth from lbs/oz to total ounces
- pregnancies$totalwgt_oz = pregnancies$birthwgt_lb * 16 + pregnancies$birthwgt_oz
- rFields <- data.frame(name = c('caseid'),
- begin = c(1),
- end = c(12)
- )
- rFields$width <- rFields$end - rFields$begin + 1
- rFields$skip <- (-c(rFields$begin[-1]-rFields$end[-nrow(rFields)]-1,0))
- widths <- c(t(rFields[,4:5]))
- widths <- widths[widths!=0]
- respondents <- read.fwf("2002FemResp.dat", widths)
- names(respondents) <- rFields$name
- str(respondents)
- str(pregnancies)
Advertisement
Add Comment
Please, Sign In to add comment