Home > Enterprise >  How can I add percentages to my flextable?
How can I add percentages to my flextable?

Time:11-05

I would like to add percentages to my flextable as another column. My object that I am working with is a list. I am new to flextables and still trying to figure them out. I would like the percentages to include missing.

Here is my data:

table_list<-list(A03.PREDIABETES = structure(list(Var1 = structure(1:2, levels = c("N", 
"Y"), class = "factor"), Freq = c(8L, 3L)), class = "data.frame", row.names = c(NA, 
-2L)), A03.GOITER = structure(list(Var1 = structure(1L, levels = "N", class = "factor"), 
    Freq = 11L), class = "data.frame", row.names = c(NA, -1L)), 
    A03.GESTATIONAL = structure(list(Var1 = structure(1:2, levels = c("N", 
    "Y"), class = "factor"), Freq = c(9L, 2L)), class = "data.frame", row.names = c(NA, 
    -2L)), A03.HASHIMOTO = structure(list(Var1 = structure(1L, levels = "N", class = "factor"), 
        Freq = 11L), class = "data.frame", row.names = c(NA, 
    -1L)), A03.THYROID = structure(list(Var1 = structure(1:2, levels = c("N", 
    "Y"), class = "factor"), Freq = c(10L, 1L)), class = "data.frame", row.names = c(NA, 
    -2L)), A03.HYPERTHYROID = structure(list(Var1 = structure(1:2, levels = c("N", 
    "Y"), class = "factor"), Freq = c(10L, 1L)), class = "data.frame", row.names = c(NA, 
    -2L)), A03.HYPOTHYROID = structure(list(Var1 = structure(1L, levels = "N", class = "factor"), 
        Freq = 11L), class = "data.frame", row.names = c(NA, 
    -1L)), A03.OTHER = structure(list(Var1 = structure(1:2, levels = c("N", 
    "Y"), class = "factor"), Freq = c(10L, 1L)), class = "data.frame", row.names = c(NA, 
    -2L)), A03.NONE = structure(list(Var1 = structure(1:2, levels = c("N", 
    "Y"), class = "factor"), Freq = c(7L, 4L)), class = "data.frame", row.names = c(NA, 
    -2L)))

Here is my code:

library(data.table)
library(tidyverse)
library(dplyr)
library(ggplot2)
library(writexl)
library(anytime)
library(officer)
library(flextable)

doc <- read_docx()

for(i in 1:length(table_list)){
  tbl <- table_list[[i]] |> 
    flextable() |> 
    set_table_properties(width = 0.5) |> 
    set_caption(names(table_list)[[i]])
  
  doc <- doc |> body_add_flextable(tbl)
}

print(doc, target = "report.docx")

CodePudding user response:

You can divide each Freq in your table by sum(Freq). To avoid column texts wrapping, I replaced your set_table_properties(width = 0.5) with flextable::autofit

library(officer)
library(flextable)
library(dplyr)

doc <- read_docx()

for(i in 1:length(table_list)){
  tbl <- table_list[[i]] |> 
    mutate(percentage = round(Freq/sum(Freq), 2)) |>
    flextable() |> 
    autofit() |> 
    set_caption(names(table_list)[[i]])
  
  doc <- doc |> body_add_flextable(tbl)
}  

print(doc, target="report.docx")

output:

enter image description here

  • Related