htmlrquarto

Unecessarily large column widths in HTML tables published by R Quarto when the table header contains special characters


All,

I am trying to render an HTML table in R Quarto of with a header that contains special characters. I can render the table correctly correctly by specifying the characters in HTML and passing escape=FALSE to knitr::kable(). However, the column width in the final column is based upon the width of the raw characters, not the number final rendered characters.

For example, the following code

#| eval: true

dof <- c(1, 2, 5, 10, 20, 50, 100, 1000, 10000)
df <- crossing(df1 = dof, df2 = dof) |> 
  mutate(fval = qf(0.05, df1, df2, lower.tail=FALSE)) |>
  pivot_wider(names_from=df2, values_from=fval)

knitr::kable(df, digits = 2, escape=FALSE,
    col.names=c("&nu;<sub>1</sub> / &nu;<sub>2</sub>", tail(colnames(df),-1)))

renders as

Rendered table with first column width much wider than rendered content

with an unnecessarily large column one width, because the column width is determined by the number of raw characters &nu;<sub>1</sub> / &nu;<sub>2</sub> and not the number of rendered characters ν1 / ν2:

Rendered table showing reason for extra wide first column

Is there a way to get the HTML column widths to automatically-resize to the rendered content?

Thanks,

Sean


Solution

  • You could try out reactable:

    ---
    format: html
    ---
    
    ```{r}
    library(dplyr)
    library(tidyr)
    dof <- c(1, 2, 5, 10, 20, 50, 100, 1000, 10000)
    df <- crossing(df1 = dof, df2 = dof) |> 
      mutate(fval = qf(0.05, df1, df2, lower.tail=FALSE)) |>
      pivot_wider(names_from=df2, values_from=fval)
    
    reactable::reactable(df, 
                         defaultColDef = reactable::colDef(
        format = reactable::colFormat(digits = 1),
        align = "center",
        minWidth = 70,
        headerStyle = list(background = "#f7f7f8")
      ),
                         columns = list(
      df1 = reactable::colDef(name = "&nu;<sub>1</sub> / &nu;<sub>2</sub>", html = TRUE)
    ))
    ```
    

    enter image description here