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

How to embed an image in a cell a table using R and Shiny?

我正在尝试创建一个书籍目录,需要帮助在我正在使用的 table.The 代码中的单元格中渲染图像,我正在使用下面的代码,我从 shiny 应用程序的代码中获得的输出是table 列 'image' 但在其单元格中包含图像的 link 而不是 Image.How 我可以更正这个吗?请帮帮我 数据集中的 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 做过类似的事情,事实上你也可以用它添加各种格式到你的 table,试试这个例如:

库和样本数据

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_... 系列函数以任何您喜欢的方式设置 table 的格式,例如 add_css_table(css = list('text-align', 'center')) 通过 table 将文本居中对齐.

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