rexport-to-word

Formatting and exporting a data frame for Word in R


I have a simple dataframe I am trying to export to a word document. I am working with ReporteRs. I want all number to be at the center of the cell (both in the body and the header).

a <- 1:5
b <- 1:5
df <- data.frame(a,b)

According to the documentation "Use ft_object[] <- value to perform the operation on the whole part (body, header or footer) of the FlexTable."

So I try

df_Flex <- FlexTable(df)
setFlexTableWidths(df_Flex, rep(0.5,2))
df_Flex[] <- parProperties(text.align = 'center')

Yet, the results is a table with only the number in the body being at the center. The header is not. If I want both the header and the body to be at the center I have to write two lines of code

df_Flex[] <- parProperties(text.align = 'center')
df_Flex[,,to='header'] <- parProperties(text.align = 'center')

which is annoying because if I want to perform other formatting I will need to write the code twice each time.

Does anyone know why this happens and how to solve the problem?


Solution

  • Use the functions provided in the flextable package itself, rather than in reporteRs, as these provide a much simpler interface for modifying the body and header parameters. An example using the pipe operator from magrittr or dplyr:

    df_Flex2 = 
      regulartable(df) %>%
      width(width = c(0.5, 2)) %>%
      align(align = "center", part = "all")
    

    Edit: Formatting decimal places

    To control the number of decimal places shown for non-integer values in a regulartable use the set_formatter function with custom formatting for each column you want to display with different decimal places:

    df_Flex2 = 
      regulartable(df) %>%
      set_formatter(a = function(x) sprintf("%.1f", x),
                    b = function(x) sprintf("%.1f", x)) %>%
      width(width = c(0.5, 2)) %>%
      align(align = "center", part = "all")
    df_Flex2
    

    Output:

    enter image description here

    If you don't want to name individual columns you can set a revised default for numeric double types by using set_formatter_type in place of set_formatter. This example sets the number of decimal places for doubles in the regulartable to 1 decimal place in a piped expression:

    set_formatter_type(fmt_double = "%.1f")
    

    If not used with the pipe (%>%) you'd need to supply the name of the regulartable variable as the first argument:

    set_formatter_type(df_Flex2, fmt_double = "%.1f")