Converted ddply to loop to increase speed