Working code updated with tapply