How to sum a variable by group in R

+4 votes

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

x<-data.frame(Players=c("Player1","Player2","Player3","Player2","Player3","Player1"),points=c(10,20,30,13,17,18))

 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

 

Apr 13, 2018 in Data Analytics by Dynamic_Coder22
• 180 points
80,062 views
how could I use mutate in dplyr to add variable x into the dataframe

Hi, @Jackiechan,

mutate(): compute and add new variables into a data table. It preserves existing variables. Look at the below picture for better understanding.

Eg: my_data %>% mutate(data_frama, X = [existing_var])

I hope this will be helpful.

3 answers to this question.

0 votes

Easily by using Aggregate Func():


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

or By Using tapply:

tapply(x$points, x$Players, FUN=sum)
answered Apr 13, 2018 by CodingByHeart77
• 3,750 points

edited Apr 13, 2018 by CodingByHeart77
+1 vote

You can also try this way,

x_new = x %>% group_by(Players) %>% summarise(x = sum(points))

Become a proficient Data Analyst with our comprehensive Data Analyst Course.

answered Aug 1, 2019 by Cherukuri
• 33,050 points
The first operator, i.e., the one after x_new, should be <- not =.