R code fully implemented and commented