Evan said that the brown drawing was a mouse. ]]>

The software company GGASoftware has extended the work of myself and others on the `sas7bdat` R package by developing a Java library called Parso, which also reads `sas7bdat` files. They have worked out most of the remaining kinks. For example, the Parso library reads `sas7bdat` files with compressed data (i.e., written with `COMPRESS=yes` or `COMPRESS=binary`). I hope to eventually bring the project full circle, and incorporate their improvements into the sas7bdat file format documentation and code in the `sas7bdat` package.

The Parso library is made available under terms of the GPLv3, and is also available under a commercial license. So, last weekend, with the help of Tobias Verbeke's `helloJavaWorld` R package template, I implemented an R package that wraps the functionality of the Parso library. The new package, `sas7bdat.parso` (currently hosted exclusively on GitHub), depends on the R package `rJava`, and implements the functions `s7b2csv` and `read.sas7bdat.parso`. The former function is the workhorse, which reads a sas7bdat file and writes a corresponding CSV file. All of the file input/output happens in the Java implementation (for speed and simplicity). The latter function `read.sas7bdat.parso` simply converts a sas7bdat file to temporary (i.e., using `tempfile`) CSV file, and then reads the CSV file using `read.csv`. There may still be some kinks the the Parso library, or in the wrapper R package, but I hope that this additional resource will help finally eliminate the SAS data file barrier that many of us have experienced for years.

Installation of the R package `rJava` is more complicated than simply calling `install.packages("rJava")`. In order for the `rJava` package to work, and hence the `sas7bdat.parso` package, a JDK (Java Development Kit) must be installed. You can download the Oracle JDK from the Oracle website. Once the JDK is installed, the easiest way to install the `sas7bdat.parso` library is using the `install_github` function in the `devtools` package (e.g., `library("devtools"); install_github("biostatmatt/sas7bdat.parso")`). For additional details on installing the `rJava` package, see the RForge site.

set.seed(42) # Consider an infinite population where the association # between two variables x and y is described by the following: # y = x^2 + e # x ~ U(0, 15) # e ~ N(0, 10) # We seek a linear approximation of the relationship between # x and y that takes the form below, and minimizes the average # squared deviation (i.e., the 'best' approximation). # hat(y) = a + b*x # This function simulates "n" observations from the population. simulate <- function(n=20) { x <- runif(n, 0, 15) y <- rnorm(n, x^2, 10) data.frame(y=y,x=x) } # This function finds the 'sample' best linear approximation to the # relationship between x and y. sam_fit <- function(dat) lm(y ~ x, data=dat) # We can approximate the 'population' best linear approximation by # taking a very large sample. Note that this only works well for # statistics that converge to a population quantity. pop_fit <- sam_fit(simulate(1e6)) ## > pop_fit ## ## Call: ## lm(formula = y ~ x, data = simulate(1e+06)) ## ## Coefficients: ## (Intercept) x ## -37.53 15.00

The figure below illustrates the true quadratic curve and the best linear approximation (`pop_fit`), overlaid against 10000 samples.

# This function creates a level confidence region for the intercept # and slope of the best linear approximation, and tests whether # the region includes the corresponding population values. # The 'adj' parameter adjusts the critical value, making the # confidence region larger or smaller. sam_int <- function(dat, val=c(a=0, b=0), level=0.95, adj=0.00) { s <- sam_fit(dat) d <- coef(s) - val v <- vcov(s) c <- qchisq(level+adj, 2) as.numeric(d %*% solve(v) %*% d) < c } # By specifying that the region has 95% confidence, we intend that # the region includes the population quantity in 95% of samples. # We can assess the coverage of the above 95% confidence region by # drawing repeated samples from the population and checking whether # the associated confidence regions include the population values: coverage20 <- mean(replicate(1e4, sam_int(simulate(20), val=coef(pop_fit)))) ## > coverage20 ## [1] 0.855 # Because the true coverage is less than the nominal coverage, # the confidence region is anti-conservative. However, suppose that # we can adjust the critical value of the region so that the true # coverage is equal to the nominal value: coverage20a <- mean(replicate(1e4, sam_int(simulate(20), val=coef(pop_fit), adj=0.045))) ## > coverage20a ## [1] 0.9476

The code above illustrates that if we had access to a population, we can adjust the coverage of a confidence region to be correct. The animation (created using Yihui's animation package) below illustrates the original and corrected confidence regions for ten different samples of size 20, overlaid against 10000 sample estimates of `a` and `b`. Unfortunately, we don't generally have access to the population. Hence, the adjustment must be made by an alternative, empirical, mechanism. In the next post, I will show how to use iterated Monte Carlo (specifically the double bootstrap) to make such an adjustment.

In the prediction framework, we use model diagnostics to verify that the model fits well, which has a direct bearing on the quality of predictions. For example, a line generally does not approximate a quadratic curve. However, it is possible to make accurate inferences about a linear approximation to a quadratic curve. Hence, model fit is not required to make quality inferences. Rather, the requirement is that the associated probability statements are correct.

Assessing model diagnostics is an indirect mechanism to comfort ourselves about the quality of inferences. As an alternative, we might attempt a more direct check, for example, by constructing an empirical estimate of coverage. We may then go further and adjust, or calibrate, the confidence interval to have the correct empirical coverage. These ideas are fundamental parts of the 'double bootstrap', and 'iterated Monte Carlo' methods. For the sake of argument, I will state that this type of empirical check and calibration is sufficient to fully replace model diagnostics for statistical inference. It is also my hypothesis that model diagnostics have been historically favored to iterative Monte Carlo methods (the double bootstrap appeared in the late 1980's) because the latter is more computationally intensive. Current computational tools mitigate, but do not eliminate this concern.

I will present examples with R code in a later post.

]]>#!/bin/sh REXEC="/usr/local/bin/R --vanilla --slave" $REXEC <<EOF # create a random file name pngfile <- paste0(format(Sys.time(), "%Y%m%d%H%M%S"), paste(sample(letters,10), collapse=""), ".png") # create temporary graphic file png(pngfile, type = "cairo") x <- seq(-10, 10, length= 30) y <- x f <- function(x, y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r } z <- outer(x, y, f) z[is.na(z)] <- 1 op <- par(bg = rgb(1,1,1,0)) persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue") persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue", ltheta = 120, shade = 0.75, ticktype = "detailed", xlab = "X", ylab = "Y", zlab = "Sinc( r )") invisible(dev.off()) # write headers pngsize <- file.info(pngfile)[["size"]] cat("Content-type: image/png\n") cat(paste("Content-length: ", pngsize, "\n\n", sep="")) # open pipe to stdout and pass image data con <- pipe("cat", "wb") writeBin(readBin(pngfile, 'raw', n=pngsize), con) flush(con) close(con) # remove intermediate graphic invisible(file.remove(pngfile)) EOF ###]]>

We have a loan with Volkswagen Credit (VC), and today received an offer to postpone our December payment of $447.50, for a small fee of $25. VC does a good job of making the offer read like a friendly holiday gesture:

'Tis the season to spread holiday cheer and join in the spirit of giving. That's why Volkswagen Credit wants to thank loyal customers like you by offering the opportunity to skip your December 2013 payment...

This is a terrible opportunity! It's essentially a new, one month loan. The annualized simple interest rate paid to VC on this loan would have been 25 / 447.50 * 100 * 12 = 67%! That would be considered usurious in Canada.

]]>Below is the type of graphic that I had initially created. It's a binary calibration plot; it plots model predictions (probabilities) against empirical estimates of the outcome probability using a kernel smoother. The kernel smoother isn't optimal because it's prone to bias, especially near the extreme predictions. This is clear in the figure below, near the origin. Although the simulated data are perfectly calibrated, the figure might lead us to conclude otherwise for predictions near zero. A 95% pointwise confidence band, and a (inverted) histogram of model predictions are also displayed.

> set.seed(42) > x <- rbeta(5000, 1, 5) > y <- rbinom(5000, 1, x) > calib(y, x, sx = seq(min(x), max(x), + length.out=100))

For completeness, listed below are the two functions that implement the kernel smoothing and calibration plot, respectively. However, the recipe for faceting with base R, outlined below, is agnostic to the type of plot used.

# binary kernel smoothing, with pointwise confidence band # y - vector of binary outcomes # x - vector of probabilities # bw - bandwidth # sx - values of x where p(y|x) is estimated # conf - confidence level for pointwise confidence band bks <- function(y, x, bw = 0.0075, sx = x, conf = 0.95) { # normal kernel estimate lsx <- length(sx); lx <- length(x) kmat <- matrix(rep(x, lsx), lsx, lx, TRUE) wts <- exp(-(kmat - sx)^2/bw) rsm <- rowSums(wts) sms <- wts %*% y est <- sms / rsm # Clopper-Pearson intervals clo <- qbeta((1-conf)/2, sms, rsm - sms + 1) chi <- qbeta(1-(1-conf)/2, sms + 1, rsm - sms) list(x = sx, est = est, clo = clo, chi = chi, conf = conf) } # Calibration curve # y - vector of binary outcomes # x - vector of probabilities (predictions) # bw - bandwidth # sx - values of x where p(y|x) is estimated # conf - confidence level for pointwise confidence band calib <- function(y, x, bw = 0.0075, sx = sort(x), conf = 0.95, ...) { ox <- order(x) x <- x[ox] y <- y[ox] bf <- bks(y, x, bw, sx, conf) hx <- hist(x, breaks=100, plot=FALSE) hx$counts <- hx$counts/sum(hx$counts) plot(hx$mids, hx$counts, ylim=c(1,0), xlim=c(0,1), type='h', ann=FALSE, yaxt='n', xaxt='n', bty='n') par(new=TRUE) plot(bf$x, bf$est, type="n", xlim = c(0,1), ylim = c(0,1), xlab = "Model", ylab = "Empirical", ...) lines(range(bf$x),range(bf$x),col="darkgray") lines(bf$x, bf$est, lty=1) lines(bf$x, bf$clo, lty=2) lines(bf$x, bf$chi, lty=2) }

The conventional approach to faceting using base R functionality is to arrange whole plots (i.e., including titles, axes, and labels) in a rectangular array within a single figure. This is accomplished, for example, by setting the `mfrow` or `mfcol` parameters using the `par` function, or by using the `layout` function. The result is something similar to the following:

> par(mfrow=c(2,2)) > replicate(4, { + x <- rbeta(5000, 1, 5) + y <- rbinom(5000, 1, x) + calib(y, x, sx = seq(min(x), max(x), + length.out=100)) + })

The `mfrow` solution is not optimal in this application, for several reasons that I won't mention here. This brings me to my solution:

- Set an outer margin to be used for labels and axes.
- Eliminate the inner margin.
- Use
`mfrow`/`mfcol`. - For each plot:
- Create a plot without titles, axes, or labels.
- Add titles, axes, and labels manually.

> CalibPlot <- expression({ + x <- rbeta(5000, 1, 5) + y <- rbinom(5000, 1, x) + calib(y, x, + sx = seq(min(x), max(x), + length.out=100), + xaxt="n", yaxt="n") + }) > > par(omi=rep(1.0, 4), mar=c(0,0,0,0), mfrow=c(2,2)) > > #1,1 > eval(CalibPlot) > mtexti("Column I", 3) > > #1,2 > eval(CalibPlot) > mtexti("Column II", 3) > mtexti("Row I", 4) > > #2,1 > eval(CalibPlot) > axis(1) > mtexti("Model Probability", 1, 0.75) > axis(2) > mtexti("Empirical Probability", 2, 0.75) > > #2,2 > eval(CalibPlot) > mtexti("Row II", 4)

The function `mtexti` (not defined here) behaves similarly to `mtext`. I recently wrote about `mtexti` (see post 2522). There are many ways in which to style and automate the faceted version. I've elected to put the axes and axis labels on the bottom-left figure only, which has some drawbacks. Hence, I haven't made much effort to encapsulate this recipe for faceting within a function, since I'm not quite sure how to best display the axes, etc.

In a comment below, Sebastian gives code for the lattice version, which is easier that I had thought. Here is the result:

]]>