Dynamically calculating Percentage of total

Hi, I have a table

Var Freq
1 8
2 13
3 7
4 8
5 4
Total 40

now i want to calculate Percentage of total in of this table dynamicaly, like the table can be of many rows but it can dynamically divide every cell by total.

like below

Var Freq Total
1 8 20
2 13 32.5
3 7 17.5
4 8 20
5 4 10
Total 40 100

Hi there, so in this example I am creating a dummy tibble with variable number of rows. You just need to rerun this example each time to see row counts and values change.

library(tidyverse)

# Set up random tibble (rerun to see changes in row count and value)
num_rows = runif(n = 1, min = 10, max = 20) %>% round()
var_values = 1:num_rows
freq_values = runif(n = num_rows, min = 1, max = 10) %>% round()

my_tibble = tibble(Var = var_values,Freq = freq_values)
glimpse(my_tibble)
#> Rows: 20
#> Columns: 2
#> $ Var  <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,...
#> $ Freq <dbl> 9, 6, 3, 7, 4, 3, 3, 6, 10, 9, 3, 3, 5, 4, 8, 2, 8, 7, 3, 4

# Create % of Total column
my_tibble = my_tibble %>% 
  mutate(Freq_pct = Freq / sum(Freq, na.rm = TRUE))

# View first part of tibble
head(my_tibble)
#> # A tibble: 6 x 3
#>     Var  Freq Freq_pct
#>   <int> <dbl>    <dbl>
#> 1     1     9   0.0841
#> 2     2     6   0.0561
#> 3     3     3   0.0280
#> 4     4     7   0.0654
#> 5     5     4   0.0374
#> 6     6     3   0.0280

# Check sum of Freq_pct column is 1
sum(my_tibble$Freq_pct, na.rm = TRUE)
#> [1] 1

Created on 2020-08-13 by the reprex package (v0.3.0)

so my table is already giving Total

overall <- as.data.frame(table(dat1[[1]])) %>% adorn_totals()
i am getting out like

Var Freq
1 8
2 13
3 7
4 8
5 4
Total 40

do we have any simplest solution for this

library(tidyverse)
library(janitor)

# Set up random tibble (rerun to see changes in row count and value)
num_rows = runif(n = 1, min = 10, max = 20) %>% round()
var_values = 1:num_rows
freq_values = runif(n = num_rows, min = 1, max = 10) %>% round()

my_tibble = tibble(Var = var_values,Freq = freq_values) %>% adorn_totals()

my_tibble %>% 
  mutate(Freq_pct = Freq / last(Freq))

Nice adorn_totals function, never used that!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.