5

I have a table that I am creating for a pdf presentation using kable and kableExtra. I am wanting to group the rows and I need to use superscripts in the row group labels. I have tried several different things. Here is an example of some of the methods I have tried so far.

library(kable)
library(kableExtra)

foo <- data.frame(a = 1:10, b = 11:20, c = 21:30)

kable(foo, format = "latex", booktabs = T, row.names = FALSE, linesep = "", escape = FALSE) %>%
  kable_styling(latex_options = c("striped")) %>%
  group_rows("Group1<sup>a</sup>", 1, 2) %>% 
  group_rows(paste0("Group2", footnote_marker_alphabet(1), sep = ""), 3, 4) %>% 
  group_rows(expression("Group3"^a), 5, 6) %>% 
  group_rows("Group4\\textsuperscript{a}", 7, 8)

I have run out of ideas and haven't been able to find any additional suggest in my search.

jamesguy0121
  • 1,124
  • 11
  • 28

1 Answers1

6

You need escape=FALSE in your group_rows() calls to allow the latex commands to be interpreted. You also seem to need to double each backslash (I don't quite understand why). After that, there are a few different options that work:

kable(foo, format = "latex", booktabs = T, row.names = FALSE, linesep = "", escape = FALSE) %>%
  kable_styling(latex_options = c("striped")) %>%
  group_rows("$\\\\text{Group1}^a$", 1, 2, escape = FALSE) %>% 
  group_rows(paste0("Group2\\\\", footnote_marker_alphabet(1), sep = ""), 3, 4, escape = FALSE) %>% 
  # I don't think expression() is helpful, doesn't seem to get converted
  # to latex
  group_rows(expression("Group3"^a), 5, 6) %>% 
  group_rows("Group4\\\\textsuperscript{a}", 7, 8, escape = FALSE)
Marius
  • 58,213
  • 16
  • 107
  • 105
  • Ahh, hadn't seen escape used in group_rows before. Should have looked more at the documentation I suppose. The option for group1 and group4 are working for me, but for some reason the group2 one is not. I can use one of the two options that work. Thank you! – jamesguy0121 Aug 29 '18 at 17:57
  • 1
    I figured out why the option for group two was not working. `footnote_marker_alphabet` inherits its format from the global option `knitr.table.format` which I do not have set. In this case it should be `group_rows(paste0("Group2\\\\", footnote_marker_alphabet(1, format = "latex"), sep = ""), 3, 4, escape = FALSE)`. – jamesguy0121 Aug 29 '18 at 18:39
  • Add the argument `double_escape = TRUE` to `group_rows()` in order to avoid needing to double the backslashes. i.e. `group_rows(paste0("Group2", footnote_marker_alphabet(1, format = "latex", double_escape = TRUE), sep = ""), 3, 4, escape = FALSE)` – pyg Jun 02 '19 at 10:06