如何使用DT、R和Shiny将图像嵌入表格单元格中

21
我该如何在使用DT包生成的单元格中嵌入图像,以便在使用shiny的应用程序中显示?这是我的示例,基于这个问题 R shiny: 如何将本地图像放入shiny表格中。下面的示例代码不会显示图像,而只会显示url。
# ui.R
require(shiny)
library(DT)

shinyUI(
  DT::dataTableOutput('mytable')
)

# Server.R
library(shiny)
library(DT)


dat <- data.frame(
  country = c('USA', 'China'),
  flag = c('<img src="test.png" height="52"></img>',
           '<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/200px-Flag_of_the_People%27s_Republic_of_China.svg.png" height="52"></img>'
           )
)

shinyServer(function(input, output){
  output$mytable <- DT::renderDataTable({

    DT::datatable(dat)
  })
})
3个回答

37

您可以在DT调用中使用escape = FALSE,如下所示:https://rstudio.github.io/DT/#escaping-table-content

# ui.R
require(shiny)
library(DT)

shinyUI(
  DT::dataTableOutput('mytable')
)

# Server.R
library(shiny)
library(DT)


dat <- data.frame(
  country = c('USA', 'China'),
  flag = c('<img src="test.png" height="52"></img>',
           '<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/200px-Flag_of_the_People%27s_Republic_of_China.svg.png" height="52"></img>'
           )
)

shinyServer(function(input, output){
  output$mytable <- DT::renderDataTable({

    DT::datatable(dat, escape = FALSE) # HERE
  })
})

使用DT处理图片


1
此时此刻,它对我来说无法工作。这可能是因为包中有一些更改吗? - Fisseha Berhane
@FissehaBerhane 建议您使用MWE(最小工作示例)打开一个新问题。 - Brandon Bertelsen
这个答案可能对服务器上的图片有所帮助 https://dev59.com/d1YN5IYBdhLWcg3wNVwW - Roman

1

2021年的小更新:

require(shiny)
library(DT)

shinyUI <- DT::dataTableOutput('mytable')

dat <- data.frame(
  country = c('China'),
  flag = c('<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/200px-Flag_of_the_People%27s_Republic_of_China.svg.png" height="52"></img>'
  )
)

#now this is a function
shinyServer <- function(input, output){
  output$mytable <- DT::renderDataTable({
    
    DT::datatable(dat, escape = FALSE) # HERE
  })
}

#minor change to make it runnable
shinyApp(shinyUI, shinyServer)

1
你能否请修改你的回答并解释你所做的更改及其原因?这将使它对未来的观众更有用。 - Cody Gray

0
我的解决方案如下: 将shinyServer(function(input,output)更改为将函数分配给shinyServer < - function

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接