Using R's way of iterating efficiently