Removed for loops and improved performance of r script