R caption contains "&" Misplaced Alignment tabs

Viewed 235

I have a kable table that works normally, but as the amount of tables I need per 'user' is more than a page, I need to add a caption in order for the tables to be comprehensible. I have the following code.

name <- "This & That"
kable(head(mtcars),
  format = "latex",
  row.names = FALSE,
 caption = paste(as.character(sub("&", "\\&",name)), "Car Score Input")) %>%
  kable_styling(full_width = FALSE, font_size = 10,latex_options = "HOLD_position", position = "left") %>%
 row_spec(row = 0, bold = TRUE, underline = F, background = "orange", color = "white", italic = FALSE, monospace = FALSE, strikeout = FALSE)%>% 
print(floating = FALSE, row.names = FALSE)

as an example. the name variable is sometimes something like "This & That" originally, I just had 'name' in the paste function but I get the following error:

! Misplaced alignment tab character &.
<argument> ...ab:unnamed-chunk-6} This & That Car Score Input}

name changes and goes through a bunch of other names, some with ampersand and some without

As you can see, I've found some forums that advise for adding \\ to the front of the character to avoid it thinking it is an escape code, but it seems no matter what I try I cannot get it to be thought of as a character. the as.character(sub("&", "\\&", name)) has been nested, I tried sub alone, before pairing it with as.character I'm just running out of ideas. The kable eventually loops through a variety of names, I even tried assigning the sub function output to name prior to adding it to the caption, it does appear as This \\& That however, I get the same error in the caption.

1 Answers

You need to escape the \\& with an additional pair of backslashes \\\\&:


library(kableExtra)

name <- "This & That"

kable(head(mtcars),
      format = "latex",
      row.names = FALSE,
      caption = paste(as.character(sub("&", "\\\\&", name)), "Car Score Input")) %>%
  kable_styling(full_width = FALSE, font_size = 10,latex_options = "HOLD_position", position = "left") %>%
  row_spec(row = 0, bold = TRUE, underline = F, background = "orange", color = "white", italic = FALSE, monospace = FALSE, strikeout = FALSE)%>% 
  print(floating = FALSE, row.names = FALSE)



enter image description here

Related