列中每个固定文本的超链接

时间:2019-04-02 10:15:12

标签: r dataframe hyperlink shiny concatenation

在下面的示例中,我必须在列3中为每个“ ID”字符串放置一个超链接。但是,下面的代码在列的每一行上以sapply循环,并且grepl返回{{1 }}或TRUE。我该如何解决?

FALSE

编辑: 如果Col3类似于:

 shinyApp(
        shinyUI(
            fluidPage(
                dataTableOutput('PM_output')
            )
        ),
        shinyServer(function(input, output, session) {
            require(DT)
            dat <- read.table(text="Col1     Col2                  Col3
              Google   '5 lines description'   'ID273, ID288, ID299'
              Yahoo    '5 lines description'   'ID3, ID28, ID2'", header=T, strings=F)
            dat$Col3 <- sapply(grepl('ID',dat$Col3), function(x) 
                toString(tags$a(href=paste0("http://id=", x), x)))

            output$PM_output <- renderDataTable(expr = datatable(dat, escape=FALSE),
              options = list(autoWidth = T))
        })
    )

如何以仅 Col3 'Name=ID273, ID288, ID299;' 'Name=ID273;' 部分为超链接的方式修复代码?

1 个答案:

答案 0 :(得分:1)

您只能为此paste0。如果您在paste中使用向量,则向量中每个元素的元素将分别串联在一起。在示例中,我为包含至少1个ID字符串的每一行中的每个ID创建了lapply超链接。

strsplit函数创建ID字符串的向量,并在每个逗号处将其分开。我添加了trimws来删除ID周围的空格。

此外,您需要将选项放在datatable函数中,并确保您没有使用我更喜欢的shiny的{​​{1}}和dataTableOutput函数将renderDataTable放在这些函数之前。

工作示例

DT::

修改

如果我理解正确,则您请求的第1行的输出是:

library(DT) library(shiny) shinyApp( shinyUI( fluidPage( DT::dataTableOutput('PM_output') ) ), shinyServer(function(input, output, session) { dat <- read.table(text="Col1 Col2 Col3 Google '5 lines description' 'ID273, ID288, ID299' Yahoo '5 lines description' 'ID3, ID28, ID2'", header=T, strings=F) dat$Col3[grepl('ID',dat$Col3)] = lapply(dat$Col3[grepl('ID',dat$Col3)], function(x)paste0("<a href=\"http://id=", trimws(unlist(strsplit(x, ',',fixed=T))), "\">", trimws(unlist(strsplit(x, ',',fixed=T))),"</a>")) output$PM_output <- DT::renderDataTable({ datatable(dat, escape=FALSE, options = list(autoWidth = T))}) }) )

您可以使用以下方法创建它:

"Name=<a href=\"http://id=ID273\">ID273</a>,<a href=\"http://id=ID288\">ID288</a>,<a href=\"http://id=ID299\">ID299</a>;"