Yomi.blaze93
Yomi.blaze93

Reputation: 425

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.

Upvotes: 0

Views: 1891

Answers (2)

Jul
Jul

Reputation: 1139

I think what you need can be done with just dplyr. But if you to export the table elsewhere, Ronak's guide to using gt should be enough.

library(dplyr)
##This is just to recreate your data set 
Combined <- structure(list(`Processing Server` = c("linode", "vpn-100", "vpn-45", "vpn-81", "vpn-98"), 
Transaction_count = c(2978, 324841, 9590, 131352, 150314),  
Face_value = c(557600, 108998381, 4975880, 55503635, 54759542)),  
row.names = c(NA, -5L),  class = c("tbl_df", "tbl","data.frame"))

##Using dplyr and base R's format function.. 
Combined %>% 
          mutate(Count_contribution = paste0(round(Transaction_count/sum(Transaction_count)*100,0),"%"),
                 Transaction_count=format(Transaction_count,big.mark=","),
                 Face_value=paste0("$",format(Face_value,big.mark=",",trim=T)))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

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

Upvotes: 1

Related Questions