How to sum a variable by group in R?

0 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
• 140 points
10,442 views

2 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,690 points

edited Apr 13, 2018 by CodingByHeart77
0 votes
You can also try this way,

x_new = x %>% group_by(Players) %>% summarise(x = sum(points))
answered Jul 31 by Cherukuri
• 31,840 points

Related Questions In Data Analytics

0 votes
1 answer

How to find out the sum/mean for multiple variables per group in R?

You can use the reshape2 package for ...READ MORE

answered Apr 12, 2018 in Data Analytics by DataKing99
• 8,130 points
431 views
0 votes
1 answer

How can I convert a factor variable to numeric in R ?

A factor variable can be converted to ...READ MORE

answered Sep 18, 2018 in Data Analytics by shams
• 3,580 points
53 views
0 votes
2 answers
+1 vote
1 answer

How do I sum the values of a variable by group but RETAIN all records?

Hey @Kirk, what you can do is, ...READ MORE

answered Jun 6 in Data Analytics by Kalgi
• 42,410 points
67 views
0 votes
1 answer

How to convert a text mining termDocumentMatrix into excel or csv in R?

By assuming that all the values are ...READ MORE

answered Apr 5, 2018 in Data Analytics by DeepCoder786
• 1,720 points
160 views
0 votes
1 answer

How to create a list of Data frames?

Basically all we have to do is ...READ MORE

answered Apr 9, 2018 in Data Analytics by DeepCoder786
• 1,720 points
104 views
0 votes
1 answer

How to spilt a column of a data frame into multiple columns

it is easily achievable by using "stringr" ...READ MORE

answered Apr 9, 2018 in Data Analytics by DeepCoder786
• 1,720 points
106 views
0 votes
2 answers

How to sort a data frame by columns in R?

You can use dplyr function arrange() like ...READ MORE

answered Aug 21 in Data Analytics by anonymous
• 31,840 points
148 views
0 votes
2 answers

How to use group by for multiple columns in dplyr, using string vector input in R?

data = data.frame(   zzz11def = sample(LETTERS[1:3], 100, replace=TRUE),   zbc123qws1 ...READ MORE

answered Aug 5 in Data Analytics by anonymous
3,585 views
0 votes
1 answer

How to create dummy variables based on a categorical variable of lists in R?

You can use mtabulate in the following way: library(qdapTools) cbind(data[1], ...READ MORE

answered Apr 13, 2018 in Data Analytics by CodingByHeart77
• 3,690 points
576 views