Added R code from @fhr.