# Chapter 3 Descriptive Syntax in R. # We begin by reading the comma-separated rat pup data file (rat_pup.dat) into R. ratpup <- read.table("C:\\temp\\rat_pup.dat", h = T) ratpup # In order to simplify reference and manipulation of the data, we will execute attach(ratpup) so that objects in the # dataset ratpup can be accessed by simply giving their names (e.g. sex rather than ratpup$sex). attach(ratpup) # To generate the stratified table on page 55, first install and load the HMisc package from a CRAN website. # This enables the use of the summarize() function in R, for stratified tables of descriptive statistics. g <- function(x)c(N=length(x),MEAN=mean(x,na.rm=TRUE),SD=sd(x,na.rm=TRUE),MIN=min(x,na.rm=TRUE),MAX=max(x,na.rm=TRUE)) summarize(weight,by=llist(treatment,sex),g) # We use boxplots to compare the distributions of birth weights for each treatment by sex combination graphically. We # first sort the data by TREAT and SEX, so that the boxplots will be displayed in the proper order. Levels of TREAT form # blocks in the boxplot output�each level of SEX is displayed within a block of TREAT. The block label position is set to # be at the bottom of the graph. library(lattice) # trellis graphics library(grid) bwplot(weight ~ sex|treatment, data=ratpup,aspect = 2, ylab="Birth Weights", xlab="SEX",main = "Boxplots of birth weights for levels of treatment by sex") # We use boxplots to illustrate the relationship between birth weight and litter size. Each panel shows the distributions # of birth weights for all litters ranked by size, within a given level of treatment and sex. We first create a new # variable, RANKLIT, to order the litters by size. The smallest litter has a size of 2 pups (RANKLIT = 1) and the largest # litter has a size of 18 pups (RANKLIT = 27). ranklit <- litsize+0.01*litter sort(ranklit) ranklit ranklit <- factor(ranklit) levels(ranklit) <- c( "1","2", "3","4","5","6","7","8","9","10", "11","12", "13","14","15","16","17","18","19","20", "21","22", "23","24","25","26","27") ranklit bwplot(weight ~ranklit | treatment*sex, data=ratpup,aspect = 2, ylab="Birth Weights", xlab="" )