Home > Net >  put brackets around negative numbers flextable
put brackets around negative numbers flextable

Time:09-29

I have a flextable composed on both positive and negative numbers.

I would like to format the negative numbers to have brackets around them, as opposed to a - sign.

ft <- flextable( data.frame(col1 = -1:1) )
ft

enter image description here

I would like to see:

enter image description here

as shown from library(formattable)'s accounting(c(-1:1))

I tried:

ft <- flextable( data.frame(col1 = -1:1) )
ft <- set_formatter( x = ft,
                     col1 = function(x) bracket_neg_num( x)
)
ft

to no avail, where bracket_neg_num:

bracket_neg_num = function(x){
  if ( x < 0){
    paste0("(",abs(x),")")
  } else if (x == 0){
    "-"
  } else{
    x
  }
}

Any suggestions?

CodePudding user response:

For vectorizing you should use ifelse like this:

library(flextable)
ft <- flextable( data.frame(col1 = -1:1) )
ft <- set_formatter( x = ft,
                     col1 = function(x) ifelse(x < 0, paste0("(",abs(x),")"), x))
ft

enter image description here

Created on 2022-09-28 with enter image description here

  • Related