rdplyrkableextra

Print emoji faces in R dataframe to KableExtra PDF/Latex instead of text


i have a data frame in R that looks like this :

# Sample data
df <- data.frame(
  Name = c("John", "Jane", "Alice"),
  Q1 = c("happy", "sad", ""),
  Q2 = c("sad", "", "happy")
)

> df
   Name    Q1    Q2
1  John happy   sad
2  Jane   sad      
3 Alice       happy



and i have two emoji faces one happy one sad stored somewhere in my computer.

#paths
happy_img = ".../happy_face.png"
sad_img   = ".../sad_face.png"

i want to print this table in PDF/latex format and with the use of Kableextra and dplyr to substitute the text happy and sad whereever occurs with the faces png.

How can i do it in R ?

(in the chunk options of rmarkdown i use results ='asis'.)


Solution

  • This solution worked for me:

    library(dplyr)
    library(knitr)
    library(kableExtra)
    
    # Sample data
    df <- data.frame(
      Name = c("John", "Jane", "Alice"),
      Q1 = c("happy", "sad", ""),
      Q2 = c("sad", "", "happy"),
      stringsAsFactors = FALSE
    )
    
    happy_img <- "happy.png"
    sad_img   <- "sad.png"
    
    # Replace text with LaTeX code that includes images
    df_mod <- df %>%
      mutate(across(c(Q1, Q2), ~ case_when(
        . == "happy" ~ paste0("\\includegraphics[width=0.05\\textwidth]{", happy_img, "}"),
        . == "sad"   ~ paste0("\\includegraphics[width=0.05\\textwidth]{", sad_img, "}"),
        TRUE ~ .
      )))
    
    
    # Print the table to LaTeX using kableExtra
    kable(df_mod, format = "latex", escape = FALSE, booktabs = TRUE) %>%
      kable_styling(latex_options = c("hold_position"))
    

    Output in PDF/LaTeX:

    enter image description here

    Note: I have images happy.png and sad.png in the same directory as the .Rmd file, and the images are 32x32 pixels in size. In order for the display to work, I had to update the knitr and Rmarkdown packages and run the command:

    install.packages("tinytex")
    tinytex::install_tinytex()
    

    Additionally, this is what the top of my .Rmd file looks like:

    title: "Some_title"
    output: pdf_document
    header-includes:
      - \usepackage{graphicx}