rr-markdownknitrkable

Adding footnotes to table with superscripting numbers in row names - rmd


As I use pack_rows(), str_replace(df, "S2", "$^{2}$") isn't working in asis_output(). Could you please provide an answer for fixing this. I add the reproducible code below,

df <- data.frame(city=c("NYCHACK IT1 N (%)","LA","CHI S2 N (%)","MIA"),
                 score=sample(1:100, 4, replace=T))

output <- df %>%
  kable("latex", booktabs = T, longtable = TRUE, align = 'l',
        caption = "caption", linesep = "") %>%
  kable_styling(position = "left", latex_options = 
                c("scale_down","hold_position"), font_size = 8) %>%
  pack_rows(index = c(" " = 1,
                      "Header 1" = 2, 
                      "Header 2" = 1)) %>%
  footnote(number = c("Footnote 1",
                      "Footnote 2"), threeparttable = TRUE)

asis_output(str_replace(output, "IT1", "$^{1}$"),
                   str_replace(output, "S2", "$^{2}$")) 

Solution

  • This has nothing to do with pack_rows. To make your code work you have to do str_replace(output, "IT1", "$^{1}$") |> str_replace("S2", "$^{2}$"), i.e. pass the result after adding the first footnote symbol into the second str_replace:

    ---
    title: "Untitled"
    output: pdf_document
    date: "2024-02-24"
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    
    library(kableExtra)
    library(knitr)
    library(stringr)
    ```
    
    ```{r}
    df <- data.frame(
      city = c("NYCHACK IT1 N (%)", "LA", "CHI S2 N (%)", "MIA"),
      score = sample(1:100, 4, replace = T)
    )
    ```
    
    ```{r}
    output <- df %>%
      kable("latex",
        booktabs = T, longtable = TRUE, align = "l",
        caption = "caption", linesep = ""
      ) %>%
      kable_styling(
        position = "left", latex_options =
          c("scale_down", "hold_position"), font_size = 8
      ) %>%
      pack_rows(index = c(
        " " = 1,
        "Header 1" = 2,
        "Header 2" = 1
      )) %>%
      footnote(number = c(
        "Footnote 1",
        "Footnote 2"
      ), threeparttable = TRUE)
    
    asis_output(
      str_replace(output, "IT1", "$^{1}$") |> 
        str_replace("S2", "$^{2}$")
    )
    ```
    

    enter image description here