rr-flextable

How to add percentages by row to flextable columns


Suppose I have a row of counts by multiple groups, and a row for the total across all groups. How can I add in a percentage by row within the same column using flextable?

For example, in this simple example, the column for setosa would read "45 (31%)":

library(dplyr)
library(datasets)
library(janitor)
library(flextable)
data(iris)

df<- iris %>%
  group_by(Species) %>%
  dplyr::summarize("Big Sepals"=sum(Sepal.Length>4.5)) %>%
  adorn_totals("row")
flextable(df)

Solution

  • To add something to an existing visible column, use append_chunks() (use prepend_chunks() to insert before existing content):

    library(dplyr)
    library(flextable)
    
    df<- iris %>%
      group_by(Species) %>%
      dplyr::summarize("Big Sepals"=sum(Sepal.Length>4.5)) %>%
      mutate(Percentage = `Big Sepals`/sum(`Big Sepals`)*100)
    
    flextable(df, col_keys = c("Species", "Big Sepals")) |> 
      append_chunks(j = "Big Sepals",
                    as_i(" ("), 
                    as_i(Percentage), 
                    as_i("%)")) |> 
      autofit()
    

    enter image description here