I just had the same problem and had a devil of a time Googling for a solution. @David-Gohel truly has the answer here, but I feel the need to provide a similar solution with additional explanation.
My problem and the OPs is that we wanted to use the data from columns that wouldn't be displayed to influence the formatting of columns that will be displayed. The concept that was not initially obvious is that you can send a data frame to flextable
with more columns than you intend to display (instead of displaying all and deleting them you've used them). Then, by using the col_keys
argument, you can select only those columns that you want to display while keeping the remaining ones around for additional processing (e.g., for using compose()
, paragraph()
, or add_chunk()
).
If I understand correctly, COLB
is supposed to be a flag to indicate that certain rows of COLC
should be modified. If so, then my solution looks like this:
library(flextable)
library(magrittr)
library(officer)
df <- data.frame(COLA=c('a', 'b', 'c'),
COLB=c('', 'changevalue', ''),
COLC=c(10, 12, 13))
ft <- flextable(df, col_keys = c("COLA", "COLC")) %>% # Retain but don't display COLB
compose(i = ~ COLB =='changevalue', # Use COLB for conditional modifications
j = "COLC",
value = as_paragraph(as_chunk('100')),
part = 'body') %>%
style(i = ~ COLB =='changevalue', # Use COLB for conditional formatting on COLC
j = "COLC",
pr_t = fp_text(color = "black",
font.size = 11,
bold = TRUE,
italic = FALSE,
underline = FALSE,
font.family = "Times New Roman"),
part = "body")
ft
And here's what the above code produces (e.g., the "changevalue" column is the trigger for conditionally inserting 100 in COLC and also for changing the formatting):
col_keys
? – Orientalize