Converted ddply to loop for better speed