Replace categorical values with traffic light colors

人盡茶涼 提交于 2019-12-12 22:44:50

问题


I have some categorical values I want to show in a table as red, yellow and green spots in R or r-markdown.

Is there a way to do this? maybe an icon package that will let me gsub text for an Icon? I have scoured the internet and come up empty handed. Any thoughts are appreciated.

library(kableExtra)
dt <- mtcars[1:5, 1:6]
kable(dt) %>%
  kable_styling(full_width = F, font_size = 12) %>%
  row_spec(0, angle = -90)%>%
  row_spec(1:5, bold = F, color = "black")


回答1:


Here's an example that uses html format in knitr. It uses the cell_spec function to make a new column using an icon and colour.

library(kableExtra)
library(emojifont)
library(dplyr)

load.fontawesome()
options(knitr.table.format = 'html')

cylcols = function(cyl) {
    case_when(
        cyl == 4 ~ 'green',
        cyl == 6 ~ 'yellow',
        cyl == 8 ~ 'red'
    )
}

dt <- 
    mtcars[1:5, 1:6] %>% 
    mutate(symbol = fontawesome('fa-circle')) %>%
        mutate(symbol = cell_spec(symbol, 'html', color=cylcols(cyl))) %>%
        select(mpg, cyl=symbol, disp, hp, drat, wt)

kable(dt, escape = F) %>%
    kable_styling(full_width = F, font_size = 12) %>%
    row_spec(0, angle = -90) %>%
    row_spec(1:5, bold = F, color = "black") 



来源:https://stackoverflow.com/questions/53566253/replace-categorical-values-with-traffic-light-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!