Completed R code for the assignment