R Percentage by Group Calculation

R Percentage by Group Calculation, The usage of this syntax in practice is demonstrated by the example that follows.

R Percentage by Group Calculation

droplevels in R with examples – Data Science Tutorials

Consider the following data frame, which displays the number of points different basketball players on different teams have scored:

Let’s create a data frame

df <- data.frame(team=c('A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'),
points=c(112, 229, 234, 104, 100, 111, 77, 136, 134, 122))

Now we can view the data frame

df
    team points
1     A    112
2     A    229
3     A    234
4     A    104
5     A    100
6     B    111
7     B     77
8     B    136
9     B    134
10    B    122

The team percentage of all points scored can be displayed in a new column in the data frame by using the following code.

Arrange Data by Month in R with example – Data Science Tutorials

library(dplyr)

Now we can calculate the percentage of points scored, grouped by team

df1<-data.frame(df %>%
  group_by(team) %>%
  mutate(percent = points/sum(points)))
df1
    team points   percent
1     A    112 0.1437741
2     A    229 0.2939666
3     A    234 0.3003851
4     A    104 0.1335045
5     A    100 0.1283697
6     B    111 0.1913793
7     B     77 0.1327586
8     B    136 0.2344828
9     B    134 0.2310345
10    B    122 0.2103448

The percentage column displays the player’s share of the team’s total points scored.

For example, players on team A scored a total of 773 points.

As a result, the individual in the first row of the data frame, who scored 112 points, accounted for 112/773 = 14% of all the points achieved by team A.

Separate a data frame column into multiple columns-tidyr Part3 (datasciencetut.com)

And so forth.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

14 − eleven =