How To Show Pipe Character In KableExtra Table In PDF?
Introduction
When working with R, it's common to use the pipe character (|
) in tables, especially when creating data frames or matrices. However, when generating PDF reports using kableExtra
and knitr
, the pipe character may not display correctly. In this article, we'll explore how to show the pipe character in kableExtra
tables in PDF reports.
Understanding the Issue
The pipe character (|
) is a special character in LaTeX, which is the underlying language used by kableExtra
to generate PDF reports. When LaTeX encounters the pipe character, it may interpret it as a delimiter or a separator, rather than a literal character. This can lead to incorrect rendering of the table in the PDF report.
Solution 1: Using the escape
Argument
One way to show the pipe character in kableExtra
tables is to use the escape
argument when calling the kable
function. The escape
argument allows you to specify whether to escape special characters in the table.
library(knitr)
library(kableExtra)

df <- data.frame(
Name = c("John", "Mary", "David"),
Age = c(25, 31, 42),
Occupation = c("Engineer", "Doctor", "Lawyer")
)
kable(df, escape = TRUE) %>%
kable_styling()
In this example, we've added the escape = TRUE
argument to the kable
function. This tells kable
to escape special characters in the table, including the pipe character.
Solution 2: Using the latex_escape
Function
Another way to show the pipe character in kableExtra
tables is to use the latex_escape
function from the knitr
package. This function allows you to escape special characters in LaTeX code.
library(knitr)
library(kableExtra)
df <- data.frame(
Name = c("John", "Mary", "David"),
Age = c(25, 31, 42),
Occupation = c("Engineer", "Doctor", "Lawyer")
)
kable(df) %>%
latex_escape() %>%
kable_styling()
In this example, we've added the latex_escape()
function to the pipeline. This escapes special characters in the LaTeX code, including the pipe character.
Solution 3: Using the pipe
Character as a Literal
A third way to show the pipe character in kableExtra
tables is to use the pipe
character as a literal character. This can be done by surrounding the pipe character with curly braces ({}
).
library(knitr)
library(kableExtra)
df <- data.frame(
Name = c("John", "Mary", "David"),
Age = c(25, 31, 42),
Occupation = c("Engineer", "Doctor", "Lawyer")
)
kable(df, format = "latex") %>%
kable_styling()
In this example, we've added the format = "latex"
argument to the kable
function. This tells kable
to generate LaTeX code for the table. We've also surrounded the pipe character with curly braces ({}
) to make it a literal character.
Conclusion
In this article, we've explored three solutions to show the pipe character in kableExtra
tables in PDF reports. By using the escape
argument, the latex_escape
function, or surrounding the pipe character with curly braces, you can ensure that the pipe character displays correctly in your PDF reports.