finished R code