Search code examples
rdplyrr-markdowntidyversegt

How to target a column and convert it to percentage


Im trying to convert the count_contribution column to a percentage

here is my code

Combined%>%
   group_by(`Processing Server`)%>%
   summarise(Transaction_count = n(), Face_value = sum(FaceValue))%>%
   mutate(Count_contribution = Transaction_count/sum(Transaction_count))%>%
  fmt_percent(columns = Count_contribution,decimals = 1)

in the Face_value column, I want to add currency

and in the count column, I want to add (,) to the count

I want it to look like this table

enter image description here

This is the error I'm getting below in markdown.

Error: The object to data is not a gt_tbl object.


Solution

  • Before applying fmt_percent or any other gt command, change the dataframe with gt() function. You can use fmt_number to add commas to number.

    Using mtcars as an example.

    library(dplyr)
    library(gt)
    
    mtcars %>%
      group_by(cyl)%>%
      summarise(Transaction_count = n() * 100, mpg = sum(mpg)) %>%
      mutate(Count_contribution = Transaction_count/sum(Transaction_count)) %>%
      gt() %>%
      fmt_percent(columns = Count_contribution,decimals = 1) %>%
      fmt_number(columns = Transaction_count)
    

    enter image description here