Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using ncol() you could do:

library(dplyr)
library(flextable)


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

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading