Search code examples
rprintfflextable

How to specify big marks separator in flextable object without using column names?


Context: I am creating .docx table using awesome package flextable. This package has a function to format numbers in the final output: set_formatter_type(). This function, if i understand correctly, requires a character input that can be used by sprintf(). I was able to acheive the expected output using set_formatter() but it required to explicitely name each column and I can not do that with my real table.

Problem: I can not find how to add big marks (e.g. thousand separator) using sprintf() synthax that works with flextable::set_formatter_type().

It is possible to acheive the right formatting using formatC() but this function does not work with flextable::set_formatter_type()

formatC(x = signif(1715235456.5684, 3), big.mark = " ", digits = 0, format = "f")
[1] "1 720 000 000"

Using sprintf() I was able to acheive:

 sprintf("%.0f", signif(1715235456.5684, 3))
[1] "1720000000"

Reproducible example:

df <- flextable::flextable(iris[1:3]*1000)
flextable::set_formatter_type(df, fmt_double = "%.0f") # works fine but I can't get big mark separator
flextable::set_formatter_type(df, fmt_double = function(x) formatC(x, digits = 0, big.mark = " ")) # does not work (error)
flextable::set_formatter(df, Sepal.Length = function(x) formatC(x, digits = 0, big.mark = " ", format = "f")) # works but I would like not to have to name each column from my real life dataframe...

Expected output:

flextable::set_formatter(df, 
                         Sepal.Length = function(x) formatC(x, digits = 0, big.mark = " ", format = "f"),
                         Sepal.Width = function(x) formatC(x, digits = 0, big.mark = " ", format = "f"),
                         Petal.Lenght = function(x) formatC(x, digits = 0, big.mark = " ", format = "f"))

Solution

  • Thanks to @TarJae and @DavidGohel comments, here is how the problem can be solved using flextable::colformat_double() function as described here: https://github.com/davidgohel/flextable/blob/master/R/formatters.R#L135

    Up to date information can be found here: https://ardata-fr.github.io/flextable-book/cell-content-1.html#simple-formatting-of-cell-content

    df <- flextable::flextable(iris[1:3]*1000)
    
    flextable::colformat_double(df, big.mark = " ", digits = 0)
    

    The output:

    enter image description here

    Credits: Formatting multiple columns with flextable r package