Search code examples
rflextable

How to dynamically choose columns in flextable package in R


I have the following table created using the flextable package in R.

library(tidyverse)
library(flextable)

data <- structure(list(Category = structure(1:2, levels = c("Baseline", 
"Alternate"), class = "factor"), `2022 Q2` = c("6%", "6.4%"), 
    `2022 Q3` = c("6.5%", "6.7%"), `2022 Q4` = c("6.4%", "6.6%"
    ), `2023 Q1` = c("5.7%", "5.5%"), `2023 Q2` = c("4.5%", "4.8%"
    ), `2023 Q3` = c("4.2%", "4.7%"), `2023 Q4` = c("4%", "4.6%"
    )), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
))

data %>% 
  flextable() %>% 
  align(j = 2:8, align = "center")

Instead of manually choosing which columns to align (j = 2:8 in this case), I would like to dynamically select all the columns from the second to the last column. I have tried align(j = 2:n(), align = "center") similar to how I would do it in dplyr, however that isn't possible in flextable notation. Any suggestions?


Solution

  • Using ncol() you could do:

    library(dplyr)
    library(flextable)
    
    
    data %>% 
      flextable() %>% 
      align(j = 2:ncol(data), align = "center")
    

    EDIT And thanks to the comment by @DavidGohel a second and preferable solution would be to use flextable::ncol_keys. The last option has the benefit that it also works in cases where only some data columns will be displayed in the flextable.

    data %>% 
      flextable() %>% 
      align(j = 2:ncol_keys(.), align = "center")
    

    enter image description here