Completed R code