Updated the R script with function code