Home > database >  Turn row values of data.table into hyperlinks that pass corresponding row values
Turn row values of data.table into hyperlinks that pass corresponding row values

Time:03-02

Lets say I have a simple data.table that and I want to pass values into google search:

library(shiny)

df1 %>% head()
   A            B
  <ch>        <ch>
1 apples      link1         
2 tomatoes    link2          
3 oranges     link3          
4 grapes      link4          
5 bananas     link5          

ui <- fluidPage(  
  titlePanel("Table with Links!"),
  sidebarLayout(
    sidebarPanel(
      h4("Click the link in the table to see
         a google search for fruit.")
    ),
    mainPanel(
      dataTableOutput('dbtable')
    )
  )
)

server <- function(input, output) {
createLink <- function(val) {
  sprintf('<a href="https://www.google.com/%s">Info</a>',val)
}



 output$dbtable <- DT::renderDataTable(DT::datatable({
    
    df1$B <- createLink(df1$A)
    return(df1)
    
    }, escape = FALSE)

}

shinyApp(ui, server)

I want to be able to turn every row in column B into a hyperlink. All the links are going to the same webpage however depending on the link clicked a different value is passed into the search bar of that webpage.

So when I click link1 google will open and pass apples as the search term. However I am getting back the hyperlink text in my data table

CodePudding user response:

We may create as a list

server <- function(input, output) {
  createLink <- function(val) {
    sprintf('<a href="https://www.google.com/#q=%s" target="_blank">Info</a>',val)
  }
  
  
  
  output$dbtable <- DT::renderDataTable({DT::datatable({
    
    df1$B <- lapply(df1$A, createLink)
    return(df1)
    
  }, escape = FALSE)
  
})
}

shinyApp(ui, server)

-output

enter image description here

  • Related