【发布时间】: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 接受现有的现有网址,该网址目前是一个字符串,并使其成为超链接。