闪亮 - 在数据表中显示网址

4

我有一个使用DT包创建的数据表,其中包含多个列,其中一列包含URL。有没有办法让用户在Shiny应用程序内点击超链接来显示这些URL呢?此外,如果URL非常长(例如随机谷歌搜索是第4个条目),是否可以仅显示前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)

这个和这个类似吗:https://dev59.com/jl4c5IYBdhLWcg3wQoc5 - Ryan Morton
@RyanMorton 靠近了,将按钮作为链接可以解决我长网址的问题。看起来链接是使用sprintf函数创建的。根据函数文档的初步研究,这只是格式化链接文本的一种方式。我相信是href函数创建链接,但我在尝试将答案适应到现有字符型网络地址上时遇到了困难,使其成为超链接。 - User247365
1个回答

2
稍微调整一下提供的代码,就能得到期望的输出结果:
createLink <- function(val) {
  sprintf(paste0('<a href="', URLdecode(val),'" target="_blank">', substr(val, 1, 25) ,'</a>'))
}
websites$url <- createLink(websites$url)

HTML的工作方式如下:<a href="LINK", otherOptions,...> 链接文本 </a> 因此,您可以使用paste0()substr()将您的链接粘贴在一起。


这个很好用!有没有办法不显示前25个字符,而是像Ryan Morton在评论中发布的帖子一样创建一个按钮?我现在有些贪心了,因为你提供的答案完全符合我在原始帖子中的要求 :) - User247365
你现在有两种方法,我猜你现在知道 ifelse() 如何工作了吧 ;) - Tonio Liebrand
我需要使用一些 if - else 逻辑来处理缺失或零长度 URL 的情况。 - jsta

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