Search code examples
rflextable

How to Spilt Long Word in Flextable?


I am creating a pdf report to display information on table using flextable. My table consists of a number of columns. One of the column ('Serial Code') contains long word and block the words of its right column. Note: In actuality, my report consists of many columns which contain long words, so it's hard to adjust the column width. I also tried autofit() but the table became out of the page. enter image description here

---
title: "Untitled"
output: pdf_document
classoption: landscape
date: "2023-07-07"
---
library(flextable)
library(dplyr)
library(data.table)

flextable(data.table("Id" = c(1:3),
                     "Name" = c("AAA", "BBB", "CCC"),
                     "Serial Code" = c("abcdefghijklmn1234567890123456789","bbcdefghijklmn1234567890123456789", "cbcdefghijklmn1234567890123456789"),
                     "Name2" = c("AAAAAA-01", "AAAAAA-02", "AAAAAA-03"),
                     "Name3" = c("BBBBBB-01", "BBBBBB-02", "BBBBBB-03"),
                     "Name4" = c("CCCCCC-01", "CCCCCC-02", "CCCCCC-03"),
                     "Name5" = c("DDDDDD-01", "DDDDDD-02", "DDDDDD-03"),
                     "Value1" = c(100000, 20000, 30000),
                     "Value2"= c(100000, 20000, 30000),
                     "Value3"= c(100000, 20000, 30000),
                     "Value4"= c(100000, 20000, 30000),
                     "Duration"= c("1 day and 2 hours", "2 days and 3 hours", "3 days and 5 hours"))) %>%
  width(width = c(0.3, 0.5, 2, 0.8, 0.9, 0.9, 0.9, 0.9, 0.6, 0.6, 0.6, 1)) %>%
  #autofit() %>%
  align(align = "left", part = "all") %>%
  fontsize(size = 10)

How to spilt the long word as below?enter image description here Your help is appreciated. Thank you.


Solution

  • If you want to break mid "word", the simplest way is to just insert a newline (\n) at fixed widths. For example, if you want to break ever 20 characters.

    theData <- data.table(
      "Id" = c(1:3),
      "Name" = c("AAA", "BBB", "CCC"),
      "Serial_Code" = c("abcdefghijklmn1234567890123456789","bbcdefghijklmn1234567890123456789", "cbcdefghijklmn1234567890123456789"),
      "Name2" = c("AAAAAA-01", "AAAAAA-02", "AAAAAA-03"),
      "Name3" = c("BBBBBB-01", "BBBBBB-02", "BBBBBB-03"),
      "Name4" = c("CCCCCC-01", "CCCCCC-02", "CCCCCC-03"),
      "Name5" = c("DDDDDD-01", "DDDDDD-02", "DDDDDD-03"),
      "Value1" = c(100000, 20000, 30000),
      "Value2"= c(100000, 20000, 30000),
      "Value3"= c(100000, 20000, 30000),
      "Value4"= c(100000, 20000, 30000),
      "Duration"= c("1 day and 2 hours", "2 days and 3 hours", "3 days and 5 hours")
    )
      
    theData |> 
      mutate(`Serial_Code` = gsub("(.{20})", "\\1\n", Serial_Code)) |> 
      flextable()