frank
frank

Reputation: 3608

flextable set_formatter by column index

I have a df:

df = data.frame(col1 = c(NA, -123.3),
                col2 = c(1234.3, NA),
                col3 = 12)
df

and I want to format the 2nd column with:

some_function = function(x, n_decimals, dash_type, suffix = ""){
  ifelse(is.na(x), 
         dash_type,
         paste0(format(round(as.numeric(x), n_decimals), nsmall=n_decimals, big.mark = ","),suffix))
}
df%>%
  flextable() %>%
  set_formatter(col2 = function(x) some_function(x,0,"-"))

which returns what I want:

enter image description here

Now, my column names change dynamically, so I want to refer to it via column position or reference, but cannot do it this way, by adding colnames(df)[2]:

enter image description here

nor adding an outside reference to the column, via x enter image description here

Is there a way to get this to work?

Upvotes: 1

Views: 369

Answers (1)

stefan
stefan

Reputation: 125897

The issue is not specific to flextable or set_formatter. TBMK for any function which expects name-value pairs you can't have a function on the LHS of the equal sign. Also, passing a name via a variable will not work.

One more or less general approach to circumvent this issue would be to use do.call which allows to pass the name-value pairs as a named list where in the code below I use a custom wrapper function:

library(flextable)
library(magrittr)

my_formatter <- function(x, fmt) {
  do.call("set_formatter", args = c(list(x = x), fmt))
}

fmt <- setNames(
  list(function(x) some_function(x, 0, "-")),
  colnames(df)[2]
)

df %>%
  flextable() %>% 
  my_formatter(fmt)

enter image description here

Upvotes: 3

Related Questions