2017-06-15 263 views
2

我有一个来自DT包的数据表,其中包含多列,其中一列包含URL。有没有一种方法可以让这些URL显示为用户可以在Shiny应用程序中单击的超链接?另外,如果URL长得令人难以置信(比如随机谷歌搜索是第四项),那么只显示前25个字符而不会破坏超链接的功能?闪亮 - 在数据表中显示URL

一些示例代码如下。

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) 

更新:基于从瑞安莫顿建议的帖子,我试图适应代码。我的问题是现在用户创建的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) 
+0

这是类似的:https://stackoverflow.com/questions/28117556/clickable-links-in-shiny-datatable –

+0

@RyanMorton接近于以及具有按钮为纽带,将解决我的问题很长的URL。看起来链接是使用sprintf函数创建的,该函数在函数文档的初始研究中只是格式化文本以用于链接的一种方式。我相信这是创建链接的href函数,但那正是我挣扎的地方,将这个答案调整为使用href,它将现有的现有网址作为当前的字符串,并将其设置为超链接。 – User247365

回答

1

稍微调整一下提供的代码,它应该得到期望的输出:

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,...> Linktext </a> 所以,你可以与paste0()substr()粘贴链接。

+0

这工作很好!有没有什么方法可以替代显示前25个字符,而是按照Ryan Morton在评论中发布的帖子创建按钮?我现在正在贪婪,因为你提供的答案完美无缺,正如我在原始文章中所提到的那样:) – User247365

+0

现在你已经有两种方法了,我想你现在应该怎么操作ifelse();) – BigDataScientist