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



我正在尝试创建一个书籍目录,需要帮助在表格的单元格中渲染闪亮的图像。我使用的代码如下,我从一个闪亮的应用程序上的代码中获得的输出是一个带有"image"列的表格,但在其单元格中包含图像的链接而不是图像。我该如何更正?请帮助我数据集中的 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)

我之前对包 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 <- 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'))整个表格将文本与中心对齐。

查看软件包的小插图,了解软件包提供的其他功能

最新更新