如何用图像自动替换列名中的文本(闪亮)?

时间:2019-08-02 07:10:39

标签: r shiny

使用过的data,我的要求是ui和服务器代码,以自动使用其徽标替换列名中的每个品牌名称。最终获得与附件图片1st image和{ {3}}

使用的代码

library(shiny)
library(DT)

ui <- fluidPage(
dataTableOutput("myTable")
)
server <- function(input, output, session) {

logoList = list(opel = "<img height='50' src='https://cdn.iconscout.com/icon/free/png-256/opel-2-202862.png'></img>",
              kia = "<img height='50' src='https://www.logospng.com/images/88/royal-azure-blue-kia-icon-free-car-logo-88484.png'></img>",
              bmw = "<img height='50' src='https://cdn.iconscout.com/icon/free/png-256/bmw-4-202746.png'></img>")

myData = reactiveVal(data.frame(testmatrix))

output$myTable = renderDataTable({
myData = myData()
myData$Manufacturer = unlist(logoList[myData$Manufacturer])

datatable(myData, escape = FALSE)
})}

1 个答案:

答案 0 :(得分:1)

如果您使用DT并包含datatable(data, escape = FALSE)标签,则图像可以包含在<img>中的任何位置,包括列名。

要自动用图像替换文本,我会使用merge,尽管有多种正确方法。

方法:

这个想法是采用表(brand, kia, vw, ...)的列名,然后将html图像标签连接到新列中。如果有图像,它将用作列名,但如果列表中没有图像,则应使用原始列名。

您最终将得到一个data.frame,如下所示:(row_id列用于确保保留列的原始顺序)

# cols    row_id      logo
# brand       1          <NA>
# kia         2     <img ...>
# vw          3          <NA>
# mit         4          <NA>
# bmw         5     <img ...>
# audi        6          <NA>
# lw          7          <NA>
# lada        8          <NA>
# RR          9          <NA>
# opel        10    <img ...>
# LBGN        11         <NA>
# Jeep        12         <NA>

完整代码:

library(shiny)
library(DT)

testmatrix <- readxl::read_xlsx("testmatrixnew.xlsx")

ui <- fluidPage(
  dataTableOutput("myTable")
)
server <- function(input, output, session) {

  logoList = data.frame(
    name = c("opel", "kia", "bmw"),
    logo = c(
      "<img height='50' src='https://cdn.iconscout.com/icon/free/png-256/opel-2-202862.png'></img>",
      "<img height='50' src='https://www.logospng.com/images/88/royal-azure-blue-kia-icon-free-car-logo-88484.png'></img>",
      "<img height='50' src='https://cdn.iconscout.com/icon/free/png-256/bmw-4-202746.png'></img>"
    ),
    stringsAsFactors = FALSE
  )

  myData = reactiveVal( {
    # Merge the image paths to the brands
    logo_name_match <- merge(
      x = data.frame(
        row_id = 1:length(colnames(testmatrix)),
        cols = colnames(testmatrix), 
        stringsAsFactors = FALSE
      ), 
      y = logoList, 
      by.x = "cols", 
      by.y = "name", 
      all.x = TRUE
    )
    # Ensure the original columnname order
    logo_name_match <- logo_name_match[with(logo_name_match, order(row_id)), ]

    # Column name should be the logo, or if no logo is found the brand
    new_colnames <- ifelse(!is.na(logo_name_match$logo), logo_name_match$logo, logo_name_match$cols)

    colnames(testmatrix) <- new_colnames
    testmatrix
  })

  output$myTable = renderDataTable({
    myData = myData()
    datatable(myData, escape = FALSE)
  })}

shinyApp(ui, server)

输出:

Output

PS ::请注意,起亚的图像链接不再起作用,这就是徽标未显示的原因。