Reputation: 3608
is it possible to dynamically format the number of decimals on a double column in a flextable dependant on the name of the row?
I have
df = data.frame(name = LETTERS[1:2], col1 = 1:2, col2 = 11:12)
df %>% flextable()
I would like to see 1 decimal place if name ==A
, and 2 decimal places if name ==B
so col1 would end up as 1.0 and 2.00
and col2 would end up as 11.0 and 12.00
any suggestions?
Upvotes: 1
Views: 621
Reputation: 124048
You could achieve your desired result using colformat_double
by passing a condition to the i
argument, e.g. i = ~name=="A"
will select the "A"
rows. However, you have to make sure that your columns are indeed of type double
. It will not work if the columns are integer
s. That's why added an additional mutate
step.
library(flextable)
library(dplyr)
df = data.frame(name = LETTERS[1:2], col1 = 1:2, col2 = 11:12)
df %>%
mutate(across(where(is.numeric), as.numeric)) %>%
flextable() %>%
colformat_double(i = ~name=="A", digits = 1) %>%
colformat_double(i = ~name=="B", digits = 2)
Upvotes: 3