Change vapply to loop