Piping through `flextable` conditional formatting

This is for some reporting that I am rendering to Word (which explains my flextable preference). I am using dplyr to aggregate the data, janitor to add a total, and finally flextable to format it, including a bold grand total.

For this last part, I am using conditional formatting based on the final row in the data frame (which contains the total). Right now, I am doing this in two steps:

library(janitor)
library(flextable)
library(dplyr)


species.count <- iris %>% 
  count(Species) %>% 
  adorn_totals() 

species.count


# I want to bold the totals

species.count <- flextable(species.count) %>% 
  bold(i = nrow(species.count), bold = TRUE)

Trying to do this in one step I get the below. I believe what is happening is that to know the number of rows in the data frame, it has to be saved to an object first, which does not happen in a pipe.

I'm grateful for any workarounds you all can think of!

iris %>% 
count(Species) %>% 
adorn_totals() %>% 
flextable() %>% 
bold(i = nrow(), bold = TRUE)

Error in nrow() : argument "x" is missing, with no default

If you want to work with tables and the pipe, then I think gt package is a better choice, take a look.

1 Like

Thanks for the tip, that's a new one to me. Will check it out.

library(janitor)
library(flextable)
library(dplyr)

species.count <- iris %>% 
  count(Species) %>% 
  adorn_totals() 

If you want to bold the totals, you can use the following code:

flextable(species.count) %>% 
  bold(i = ~ Species %in% "Total", bold = TRUE)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.