Search code examples
htmlrkableextra

How to use unicode symbols in a kableExtra HTML table


I have the following dataframe in R

data <- structure(list(Category = c("Item 1", "Item 2", "Item 3"), `Month 1` = c(-3.7, 
0.8, -2.1), `Month 2` = c(-2.1, 0.8, -3.7)), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

I'm using this dataframe to create a table using kableExtra (and ultimately rendering it in HTML format). Below, I created an extra column which uses 2 ifelse arguments (where the word "up" if Month 2 > Month 1, "down" if Month 2 < Month 1, or blank if Month 2 = Month 1). Instead of having words, I would like to use unicode symbols in this link to display arrows.

Is there a way to use unicode hex codes instead of words, so that I can have the North East Arrow for "Up", Rightwards arrow for the blank argument, and the South East Arrow for "down"?

library(kableExtra)
library(tidyverse)

data %>% 
  mutate(Trend = ifelse(.[,3] > .[,2],"Up", ifelse(.[,3] == .[,2], "",  "Down"))) %>% 
  kable() %>% 
  kable_styling()

I'm ultimately looking to replicate something along the lines of the image I've attached

enter image description here


Solution

  • Using kableExtra -

    library(dplyr)
    library(kableExtra)
    
    data %>%
      mutate(Trend = case_when(`Month 1` == `Month 2` ~ "$\\rightarrow$", 
                               `Month 2` > `Month 1` ~ "$\\uparrow$", 
                               TRUE ~ "$\\downarrow$")) %>%
      kable() %>% kable_styling()
    

    enter image description here

    Appropriate symbols can be found from this pdf.