How do I calculate Percent_of_all_samples using knitr and janitor

I am trying to create a third column in a table that shows the percentages of one other columns information out of the total. I have calculated my n values and now I just want to place that over the total number of data numbers I have. I have my two column table and this is the table I am trying to create with the third column added.

Below are two different approaches. The first uses the {janitor} package, and the second uses the {dplyr} package.

mtcars |>
  janitor::tabyl(cyl)
#>  cyl  n percent
#>    4 11 0.34375
#>    6  7 0.21875
#>    8 14 0.43750

mtcars |>
  dplyr::count(cyl) |>
  dplyr::mutate(percent = n/sum(n))
#>   cyl  n percent
#> 1   4 11 0.34375
#> 2   6  7 0.21875
#> 3   8 14 0.43750

Created on 2023-03-20 with reprex v2.0.2.9000

1 Like

Thank you, stunning!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.