Chapter 1: A Brief Introduction to R

Packages required: “DAAG”, “lattice”

The script that follows is designed to be executed as it stands. It sets up
functions that create Ch 1 graphs, then runs those functions. If executed by
clicking on the RStudio “Compile Notebook …” command, it will be processed
through R Markdown, generating a document that includes code, output and
graphs generated by executing the functions. If some needed packages are
missing, warning messages will appear. See further:
http://rmarkdown.rstudio.com/r_notebook_format.html

g1.1 <-
function(device=""){
    if(device!="")hardcopy(width=2.25,
                           height=2.25, device=device)
    oldpar <- par(mar = c(4.1,4.1,1.1,1.1), pty="s", mgp=c(2.5,0.75,0))
    on.exit(par(oldpar))
    Year <- c(1800, 1850, 1900, 1950, 2000)
    Carbon <- c(8, 54, 534, 1630, 6611)
    plot(Carbon ~ Year, pch=16, cex=1.5, tcl=-0.35)
    if(device!="")dev.off()
  }

g1.2 <-
function(device=""){
    if(device!="")hardcopy(device=device, width=2.3, height=2.3)
    oldpar <- par(mar = c(4.1,4.1,1.1,1.1), mgp=c(2.5,0.75,0),
                  cex.axis=0.875)
    on.exit(par(oldpar))
    attach(primates)
    plot(x=Bodywt, y=Brainwt, pch=16, tcl=-0.35,
         xlab="Body weight (kg)", ylab="Brain weight (g)", 
         xlim=c(0,300), ylim=c(0,1500))
    chw <- par()$cxy[1]
    chh <- par()$cxy[2]
    text(x=Bodywt, y=Brainwt+c(-.125,0,0,.125,0)*chh, 
         labels=row.names(primates), pos=4)
    detach(primates)
    if(device!="")dev.off()
  }

g1.3 <-
function(width=5, height=2.25, pointsize=c(7,5), device=""){
    if(device!="") hardcopy(width=width, height=height,
                            color=F, pointsize=pointsize,
                            trellis=TRUE, device=device)
    if(!require(lattice))return("Package 'lattice' is not installed -- cannot proceed")       
    parset <- simpleTheme(pch=c(4,1), col=c(1,1))
    ## Specify after opening any new graphics device
    here <- ais$sport %in% c("Row", "Swim")
    gph <- xyplot(ht ~ wt | sport, groups=sex, subset=here, data=ais,
                  par.settings=parset,
                  auto.key=list(space="right"), aspect=1, scales=list(tck=0.5))
    print(gph)                             
    if(device!="")dev.off()
  }

pkgs <- c("DAAG", "lattice")
z <- sapply(pkgs, require, character.only=TRUE, warn.conflicts=FALSE, quietly=TRUE)
if(any(!z)){
  notAvail <- paste(names(z)[!z], collapse=", ")
  warning(paste("The following packages should be installed:", notAvail))
}
g1.1()

plot of chunk unnamed-chunk-2

g1.2()

plot of chunk unnamed-chunk-3

g1.3()

plot of chunk unnamed-chunk-4