Completed R code for the Project