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

时间:2019-04-13 23:51:23

标签: r shiny shinydashboard shiny-server shiny-reactivity

我正在尝试创建一个书本目录,需要帮助来在表格的单元格中以闪亮的形式呈现图像。我正在使用的代码如下,从闪亮的应用程序中的代码中获得的输出是带有列“图片”,但在其单元格中而不是图片中包含图片的链接。如何解决此问题?请帮帮我 数据集中的URL格式为:https://images.gr-assets.com/books/1447303603s/2767052.jpg

数据看起来像这样

title authors ratings_count average_rating image_url HP JK 10 4 https://images.gr-assets.com/books/1447303603s/2767052.jpg

ui <- fluidPage(

  ####Heading##
  titlePanel(div(HTML("<b> Interested In books? </b>"))),

  ###Creating tabs###
  tabsetPanel(


    ####First tab for crime####
    tabPanel(" Book Directory ",
             sidebarLayout(

               sidebarPanel(

                 #First Input##
                 selectizeInput(inputId = "Book",
                                label = " Choose a Book",
                                choices = book_names)),

               ##Output
               mainPanel = (tableOutput("View")
               )
             )
    )
  )
)



###Server app
server <- function(input, output) {
  output$View <- renderTable({
    books1 <- books[books$title%in% input$Book,]
    books1  %>% 
      mutate(image = paste0('<img src="', image_url, '"></img>')) %>%  
      select(image,title,authors,average_rating,ratings_count) 
      })
}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

我之前使用tableHTML包做了类似的事情,实际上,您也可以使用它向表中添加各种格式的内容,例如:

库和样本数据

library(tableHTML)
library(shiny)
library(dplyr)
books <- read.table(text = "title authors ratings_count average_rating        image_url
 HP     JK        10            4                https://images.gr-assets.com/books/1447303603s/2767052.jpg", header=TRUE)

books_names <- unique(books$title)

UI(相同的ui):

ui <- fluidPage(
  titlePanel(div(HTML("<b> Interested In books? </b>"))),
  tabsetPanel(
    tabPanel(" Book Directory ",
             sidebarLayout(
               sidebarPanel(
                 selectizeInput(inputId = "Book",
                                label = " Choose a Book",
                                choices = books_names)),
               mainPanel = (tableOutput("View"))
             )
    )
  )
)

服务器:

server <- function(input, output) {
  output$View <- render_tableHTML({
    books[books$title%in% input$Book,] %>% 
      mutate(image = paste0('<img src="', image_url, '"></img>')) %>%  
      select(image,title,authors,average_rating,ratings_count) %>% 
      tableHTML(escape = FALSE, 
                rownames = FALSE, 
                widths = c(40, 40, 65, 120, 120)) %>% 
      # align the text like this
      add_css_table(css = list('text-align', 'center'))
      # you can also add a theme 
      # add_theme('scientific')
  })
}

运行应用程序:

shinyApp(ui = ui, server = server)

您可以使用add_css_...系列函数以任何方式设置表格格式,例如add_css_table(css = list('text-align', 'center'))使文本在整个表格中居中对齐。

看看软件包的vignettes,看看软件包提供的其他功能