How to sum a variable by group in R?

Data Science

I have a data frame of consisting two columns "Players" & "points"


Players points
1 Player1 10
2 Player2 20
3 Player3 30
4 Player2 13
5 Player3 17
6 Player1 18

I want to sort the data by players and sum the points:

Like this:

Players x
1 Player1 28
2 Player2 33
3 Player3 47




One way to do this is to use tapply by summing the points with respect to players.

tapply(x$points, x$Players, FUN=sum)


You can use the aggregate function in the following way.

aggregate(x$points, by=list(Players=x$Players), FUN=sum)


If you want to unleash your potential in this competitive field, please visit the Data Science course page for more information, where you can find the Data Science tutorials and Data Science frequently asked interview questions and answers as well.


This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
Protected by Astra Security