Search code examples
rpdfcharacter-encodingr-markdownkable

How can I add greek letters to cells in my Rmarkdown table using kable?


I'm trying to render a table in R Markdown with several cells containing Greek letters. I use the following code to generate the table:

table <- readxl::read_excel("path/to/table.xlsx", 
    sheet = "data")

table %>% 
  knitr::kable(booktabs = TRUE)

While the output in the console is exactly what I want, I get the following error message when I try to knit the file to a PDF:

! LaTeX Error: Unicode character κ (U+03BA)
               not set up for use with LaTeX.

I need to present the table with all the Greek letters. I've found information about getting Greek letters in the headings, but nothing about getting them to work in the body of the table. What is the best way to accomplish this?

Below is an example of the data I'm trying to render.

enter image description here

Any help would be very much appreciated!


Solution

  • Problems with encodings are eternal.

    I can advice to you this solution.

    Not so elegant, but it works.

    Steps in console:

    1. Activate the greek locale:

      Sys.setlocale("LC_CTYPE", "greek")

    2. Read the excel file:

      table <- readxl::read_excel("table.xlsx", sheet = "N1")

    enter image description here

    1. Generate code for LaTeX:

      table %>% knitr::kable(booktabs = TRUE, "latex")

    Now we can transfer to rmd-file:

    A simple example:

    ---
    title: "Table"
    output:
      pdf_document:
        latex_engine: xelatex
    header-includes:
    - \usepackage{polyglossia}
    - \setotherlanguage{greek}
    - \newfontfamily\greekfont[Script=Greek,Ligatures=TeX]{Times New Roman} 
    - \usepackage{booktabs}
    ---
    
    Beautiful table:
    
    \begin{greek} 
    \begin{tabular}{ll}
    \toprule
    Object1 & Object2\\
    \midrule
    ββ & λ\\
    α & φ\\
    \bottomrule
    \end{tabular}
    \end{greek}
    

    Output:

    enter image description here