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.