R script final version