Optimized R code, added local file run logic for testing