final version of R code