rr-markdownr-flextable

How do I set a flextable's overall width to 100% while two columns have fixed widths?


I have a table with three columns. The first and third should have a width of 5 cm, and the second should autofit the remainder of the space, for an overall width of 100%.

here is my minimum .rmd

---
output: html_document
---

```{r, echo=FALSE}
library(flextable)

data <- data.frame(
name = c("John", "Jane", "Tom"),
age = c(25, 30, 35),
height = c(176, 180, 178)
)

ft <- flextable(data)
ft <- set_table_properties(ft, width = 1, layout = "autofit")
ft <- width(ft, j = 1, width = 5, unit = "cm")
ft <- width(ft, j = 3, width = 5, unit = "cm")
ft <- theme_box(ft)
ft
```

I set the overall width to 100%, which works fine

ft <- set_table_properties(ft, width = 1, layout = "autofit")

and the column widths to 5 cm, which works fine without autofit

ft <- width(ft, j = 1, width = 5, unit = "cm")
ft <- width(ft, j = 3, width = 5, unit = "cm")

The table is 100%, while column widths are ignored and set by autofit. User documentation says "If layout is autofit, column widths will not be used", so I know that it won't work this way...

It would be nice if there were some way to have only the width of the second column autofitting, leaving the widths of columns one and three at 5 cm.


Solution

  • You can use opts_html + extra_css and add the style 99% to the second column (th:nth-child(2)) using CSS. This will keep the widths applied to column 1 and 3 but make the 2nd column scale with the available space.

    library(flextable)
    
    data <- data.frame(
      name = c("John", "Jane", "Tom"),
      age = c(25, 30, 35),
      height = c(176, 180, 178)
    )
    
    ft <- flextable(data)
    #ft <- set_table_properties(ft, width = 1, layout = "autofit")
    ft <- width(ft, j = 1, width = 5, unit = "cm")
    ft <- width(ft, j = 3, width = 5, unit = "cm")
    ft <- theme_box(ft)
    
    ft <- set_table_properties(
      x = ft,
      opts_html = list(
          extra_css = "
              th:nth-child(2) {
                width: 99%;
              }
          "
        )
    )
    ft
    

    giving

    out