rr-flextable

combining flextable formatting of negative numbers with NA and big mark


I have

df = data.frame(col1 = c(NA,10000,-1,0), col2 = 1:4)

I would like:

I can do it separately with:

flextable(data.frame(col1 = c(NA,10000,-1,0), col2 = 1:4)) %>%
  colformat_num(
    big.mark = ",", decimal.mark = ".",
    na_str = "N/A") 

and

flextable(data.frame(col1 = c(NA,10000,-1,0), col2 = 1:4)) %>%
  set_formatter(col1 = function(x) ifelse(x < 0, paste0("(",abs(x),")"), ifelse(x == 0, paste("-"), ifelse(is.na(x), paste("N/A"),x))))

but when combining them, does not reveal the way I would like:

flextable(data.frame(col1 = c(NA,10000,-1,0), col2 = 1:4)) %>%
  colformat_num(
    big.mark = ",", decimal.mark = ".",
    na_str = "N/A") %>%
  set_formatter(col1 = function(x) ifelse(x < 0, paste0("(",abs(x),")"), ifelse(x == 0, paste("-"), ifelse(is.na(x), paste("N/A"),x))))

I would like:

enter image description here


Solution

  • You could use format with big.mark and use set_flextable_default like this:

    library(flextable)
    library(dplyr)
    df = data.frame(col1 = c(NA,10000,-1,0), col2 = 1:4)
    set_flextable_defaults(na_str = "NA", big.mark = ",")
    flextable(data.frame(col1 = c(NA,10000,-1,0), col2 = 1:4)) %>%
      set_formatter(col1 = function(x) ifelse(x < 0, paste0("(",abs(x),")"), 
                                       ifelse(x == 0, paste("-"), 
                                       ifelse(is.na(x), "NA",
                                       ifelse(x > 100, format(x, big.mark = ','), x))))) 
    

    enter image description here

    Created on 2022-09-28 with reprex v2.0.2


    Some code for your comment:

    library(flextable)
    library(dplyr)
    df = data.frame(col1 = c(NA,10000,-1,0), col2 = 1:4)
    set_flextable_defaults(na_str = "NA", big.mark = ",")
    flextable(data.frame(col1 = c(NA,10000,-1234,0), col2 = 1:4)) %>%
      set_formatter(col1 = function(x) ifelse(x < 0, paste0("(",format(abs(x), big.mark = ','),")"), 
                                       ifelse(x == 0, paste("-"), 
                                       ifelse(is.na(x), "NA",
                                       ifelse(x > 100, format(x, big.mark = ','), x))))) 
    

    enter image description here

    Created on 2022-09-30 with reprex v2.0.2