Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use icons together with kable

Tags:

r

shiny

kable

Working on a shiny app (without rmarkdown), I would like to add a visual representation of a column to my data table. Inspired by this question, I produced

dat <- data.frame(
    what=letters[1:15],
    value=rnorm(15)
) |> transform(
    direction=ifelse(abs(value)<0.1, "&#8646;", ifelse(value<0, "&#8595;", "&#8593;"))
) |> knitr::kable(format="html", escape=FALSE) |>
    kableExtra::kable_styling() # show in browser
dat

which looks like this

Table with Ampersand

However, I would rather use shiny::icon("circle-up") like this:

down <- as.character(shiny::icon("circle-down")) # dropping as.character results in an error
up <- as.character(shiny::icon("circle-up"))
side <- as.character(shiny::icon("circle-right"))
dat <- data.frame(
    what=letters[1:15],
    value=rnorm(15)
) |> transform(
    direction=ifelse(abs(value)<0.1, side, ifelse(value<0, down, up))
) |> knitr::kable(format="html", escape=FALSE) |>
    kableExtra::kable_styling() # show in browser

but in this case, nothing is displayed:

Table with Icons

Any ideas how to use icons together with kable?

like image 589
Karsten W. Avatar asked Jan 21 '26 14:01

Karsten W.


1 Answers

Assuming you're rendering to html:

  • Force shiny to load the icon deps by including a hidden sample icon anywhere in the document.

Here's a reprex:

Icon showcase

---
title: "Icons"
output: html_document
date: "2023-07-20"
---

```{r}
up <- shiny::icon(name = "circle-up") |>  as.character()
down <- shiny::icon(name = "circle-down") |> as.character()
side <- shiny::icon(name = "circle-right") |> as.character()
dat <- data.frame(
  what = letters[1:15],
  value = rnorm(15)
) |> 
  transform(
    direction = ifelse(abs(value) < 0.1, side, ifelse(value < 0, down, up))
  ) |> knitr::kable(format = "html", escape = FALSE) |>
  kableExtra::kable_styling() # show in browser
dat
```

<!-- This will force shiny to load the icon deps: -->
```{r include=FALSE}
shiny::icon("circle-up")
```
like image 158
Mwavu Avatar answered Jan 24 '26 02:01

Mwavu