This tutorial will show you for to calculate percent of total in R. You will need the tidyverse package to run this script.
if(!require(tidyverse)) install.packages("tidyverse")
Set your seed, so you can re-create the exact output. We will create an example dataset with two columns: Color and Score. We will include 100 rows in our sample set.
set.seed(7)
df <- data.frame("Color"=c('red', 'blue', 'yellow', 'green', 'orange'),
"Score" = runif(100, 1, 99) )
head(df)
## Color Score
## 1 red 97.913111
## 2 blue 39.979054
## 3 yellow 12.338382
## 4 green 7.835371
## 5 orange 24.887440
## 6 red 78.617022
Now we will calculate the percent of total. You will see details to the right of code.
percent_of_total <- df %>% #calling the sample dataset
group_by(Color) %>% #group the column that we want to summarise
summarise(Count = length(Score), #total rows of each color
total_score = sum(Score, na.rm = TRUE), #total score per color
Percent_score = paste0(round(sum(Score * 100) /
sum(df$Score, na.rm = TRUE),1),"%"))#total score per color divided by total score color of dataset
print(percent_of_total)
## # A tibble: 5 x 4
## Color Count total_score Percent_score
## <fct> <int> <dbl> <chr>
## 1 blue 20 814. 16%
## 2 green 20 1092. 21.5%
## 3 orange 20 1027. 20.2%
## 4 red 20 994. 19.5%
## 5 yellow 20 1163. 22.9%