Is there a way to rename column names with icons
Asked Answered
W

2

5

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?

Wysocki answered 23/2, 2022 at 7:58 Comment(2)
Short answer: probably no. Check ?make.names.Jovia
Related post: https://mcmap.net/q/2031215/-why-are-the-icons-not-displaying-in-a-dt-datatable-in-shiny-app/680068Catalase
C
5

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.

Clupeoid answered 23/2, 2022 at 9:12 Comment(0)
D
4

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
Dispirit answered 23/2, 2022 at 13:39 Comment(4)
This is very interesting to me, but I'm having a difficult time adapting this my own tables. Is there a way to make your js function more general-purpose?Cenacle
@Cenacle Sorry I don't see what you want. Maybe open a new question.Fidole
Hi Stéphane Laurent, thank you for your answer. Is it possible to extend this to make it to show a short text as a description when hovering above or click the icon?Ungovernable
@Ungovernable Yes I think this is doable. Open a new question if you want.Fidole

© 2022 - 2024 — McMap. All rights reserved.