Final version of R script