retain white spaces in flextable

51 views Asked by At

How can I retain the (additional) white space of a character column in a flextable? The code sequence

flextable(data.frame("temp" = c("Lore ips", 
                                "dol  sit")))

generates the following image:

enter image description here

Note how the "ips" and "sit" subtexts would be aligned in the data.frame but are not aligned in the flextable.

2

There are 2 answers

1
David Gohel On BEST ANSWER

White spaces are indeed collapsed in HTML output. You can use a tab instead:

flextable(data.frame("temp" = c("Lore ips", "dol\tsit")))

enter image description here

Or you can add extra css instruction (for the HTML output):

set_flextable_defaults(extra_css = ".tabwid{white-space: break-spaces;}")
flextable(data.frame("temp" = c("Lore ips", "dol   sit")))

enter image description here

1
stallingOne On

You could maybe use a function to replace spaces with   like this:

library(flextable)

render_cell <- function(x) {
  return(paste0("<td>", gsub(" ", "&nbsp;", x), "</td>"))
}

ft <- flextable(
  data.frame(
    temp = c(render_cell("Lore ips"), render_cell("dol  sit"))
  )
)
ft