Search code examples
rflextable

Formatting number of decimals in rows different from column decimal formatting in Flextable


All formatting in this Flexible table is as desired, except I prefer the values in row 'n' to show no decimals. Rounding the row values does not produce the desired result.

enter image description here

library(flextable)

tab_tbl <- tibble(Date = c( "2000-12-27", "2000-12-28", "2000-12-29",  "2000-12-30", "2000-12-30", "n", "Manster"  ),
                          Col1    = c(runif(5), 5, 3.75325),
                          Col2    = c(runif(5), 5, 4.3892), 
                          Col3    = c(runif(5), 5, 5.789)
  )

tab_tbl[ , 2] <- round( tab_tbl[ , 2], 3) 
tab_tbl[ , 3:4] <- round( tab_tbl[ , 3:4], 2)
tab_tbl[6, 2:4] <- round( tab_tbl[6, 2:4], 0) 

small_border = fp_border(color="gray", width = 1)

my_table <- flextable( tab_tbl )

my_table %>%
  width(j=1:4, width = 1.2) %>%
  flextable::align(align = "center", j = c(2:4), part = "all") %>%
  hline( i=5,  border = small_border )

Solution

  • One solution is to use colformat_double(digits = 0):

    library(flextable)
    
    tab_tbl <- tibble(Date = c( "2000-12-27", "2000-12-28", "2000-12-29",  "2000-12-30", "2000-12-30", "n", "Manster"  ),
                      Col1    = c(runif(5), 5, 3.75325),
                      Col2    = c(runif(5), 5, 4.3892), 
                      Col3    = c(runif(5), 5, 5.789)
    )
    
    tab_tbl[ , 2] <- round( tab_tbl[ , 2], 3) 
    tab_tbl[ , 3:4] <- round( tab_tbl[ , 3:4], 2)
    tab_tbl[6, 2:4] <- round( tab_tbl[6, 2:4], 0) 
    
    small_border = fp_border_default(color="gray")
    
    my_table <- flextable( tab_tbl )
    
    my_table %>%
      width(j=1:4, width = 1.2) %>%
      flextable::align(align = "center", j = c(2:4), part = "all") %>%
      hline( i=5,  border = small_border ) %>% 
      colformat_double(i = ~ Date == "n", digits = 0)
    

    enter image description here