Port some of the analysis code to R