【问题标题】:Shiny - display URL's in datatableShiny - 在数据表中显示 URL
【发布时间】:2017-11-18 03:41:53
【问题描述】:

我有一个来自 DT 包的数据表,其中包含多个列,其中一个包含 URL。有没有办法让这些 URL 显示为用户可以在 Shiny 应用程序中单击的超链接?此外,如果 URL 非常长(例如作为第 4 个条目的随机 google 搜索),是否会仅显示前 25 个字符而不会破坏超链接的功能?

一些示例代码如下。

require(DT)
require(shiny)

web_names <- c("google", "yahoo", "Stack Overflow", "Random Google Search")
url <- c( "https://www.google.com/", "https://www.yahoo.com/", "https://stackoverflow.com/", "https://www.google.com/search?q=random+google+search&oq=random+google+search&aqs=chrome..69i57j0l5.3264j0j7&sourceid=chrome&ie=UTF-8")
websites <- data.frame(web_names, url)

ui <- fluidPage(
  DT::dataTableOutput("websitesTable")
)


server<-function(input,output,session) {
output$websitesTable <- DT::renderDataTable({datatable({websites})})
}

shinyApp(ui=ui, server=server)

更新:根据 Ryan Morton 的建议帖子,我尝试调整代码。我的问题现在是用户创建的 createLink 函数中包含的 sprintf 函数。链接按钮出现,但未转到所需位置。

#app.R#

library(shiny)

web_names <- c("google", "yahoo", "Stack Overflow", "Random Google Search")
url <- c( "https://www.google.com/", "https://www.yahoo.com/", "https://stackoverflow.com/", "https://www.google.com/search?q=random+google+search&oq=random+google+search&aqs=chrome..69i57j0l5.3264j0j7&sourceid=chrome&ie=UTF-8")
websites <- data.frame(web_names, url)
createLink <- function(val) {
  sprintf('<a href="" target="_blank" class="btn btn-primary">Info</a>', val)
}

websites$url_link <- createLink(websites$url)

ui <- fluidPage(  
  titlePanel("Table with Links!"),
  sidebarLayout(
    sidebarPanel(
      h4("Click the link in the table to go to the url listed.")
    ),
    mainPanel(
      dataTableOutput('table1')
    )
  )
)

server <- function(input, output) {

  output$table1 <- renderDataTable({ datatable({websites})
    return(websites)

  }, escape = FALSE)
}

shinyApp(ui, server)

【问题讨论】:

  • @RyanMorton 这很接近,有一个按钮作为链接可以解决我的长网址问题。看起来链接是使用 sprintf 函数创建的,根据函数文档的初步研究,它只是格式化要在链接中使用的文本的一种方式。我相信它是创建链接的 href 函数,但这就是我正在努力的地方,调整该答案以使用 href 接受现有的现有网址,该网址目前是一个字符串,并使其成为超链接。

标签: r shiny dt


【解决方案1】:

稍微调整提供的代码,它应该会产生所需的输出:

createLink <- function(val) {
  sprintf(paste0('<a href="', URLdecode(val),'" target="_blank">', substr(val, 1, 25) ,'</a>'))
}
websites$url <- createLink(websites$url)

HTML 像这样工作:&lt;a href="LINK", otherOptions,...&gt; Linktext &lt;/a&gt; 因此,您可以将链接与paste0()substr() 一起粘贴。

【讨论】:

  • 这很好用!有没有什么方法可以创建一个按钮,而不是显示前 25 个字符,就像 Ryan Morton 在 cmets 中发布的帖子一样?我现在很贪婪,因为您提供的答案正如我在原始帖子中所问的那样完美:)
  • 你现在有两种方法,我猜你现在ifelse()是如何工作的;)
  • 我需要使用一些 if - else 逻辑来处理 URL 丢失或长度为零的情况。
猜你喜欢
  • 2020-04-28
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多