Is there a way to rename column names with icons

Viewed 125

Is there a way to add an icon to column headers by renaming it . I tried with below

datatable((iris %>% rename(paste0('Sepal.Width',as.character(icon(name = "info-circle", lib = "font-awesome"))) = Sepal.Width)))

So I need a small icon next to Sepal.Width, so tried like above. But I am not getting any result. Can anyone help me?

2 Answers

You can use the gt package, which accepts html code as column names and the icons package which delivers the proper html code:

library(tidyverse)
library(gt)

iris %>% 
  head() %>% 
  gt() %>% 
  cols_label(
    Sepal.Width = html(as.character(icons::fontawesome("info-circle")))
  )

enter image description here

Created on 2022-02-23 by the reprex package (v2.0.1)

This displays the icon as a column name, but the column name in the data.frame is not changed. I assumed this is what you actually want, given the use of DT::datatable in your example.

Otherwise, you could use:

colnames(iris) <- c("Sepal.Length",
                    as.character(icons::fontawesome("info-circle")), 
                    "Petal.Length", 
                    "Petal.Width", 
                    "Species")

But it would be much more complicated to display the actual icon and not the underlying html code.

Maybe there's an easier way:

enter image description here

library(DT)
library(fontawesome)

js <- c(
  'function( thead, data, start, end, display ) {',
  sprintf(
    '  $(thead).find("th").eq(2).html(%s);',
    shQuote(paste0("Sepal Width ", as.character(fa_i("info-circle"))))
  ),
  '}'
)

dat <- iris[1:5, ]

dtable <- datatable(
  dat,
  options = list(
    headerCallback = JS(js)
  )
)
htmldeps <- dtable$dependencies
dtable$dependencies <- c(htmldeps, list(fa_html_dependency()))
dtable
Related