refactor R script using function