Use loop instead of apply, avoiding stack errors in some cases