Skip to content

Instantly share code, notes, and snippets.

@AdamSpannbauer
Last active June 13, 2018 12:08
Show Gist options
  • Save AdamSpannbauer/d93af343214c09c0ee7ce035dcdee5e1 to your computer and use it in GitHub Desktop.
Save AdamSpannbauer/d93af343214c09c0ee7ce035dcdee5e1 to your computer and use it in GitHub Desktop.
wordcloud2 browseURL click event
## install PR of wordcloud2 that adds click events
# devtools::install_github("Lchiffon/wordcloud2#35")
library(shiny)
library(shinyjs)
library(wordcloud2)
# define dummy data to use in example
wordcloud_df = data.frame(word = c('bing', 'google'),
freq = c(1, 2),
url = c('https://www.bing.com/',
'https://www.google.com/'),
stringsAsFactors = FALSE)
# define js function for opening urls in new tab/window
js_code = "
shinyjs.browseURL = function(url) {
window.open(url,'_blank');
}
"
shinyApp(
ui=shinyUI(fluidPage(
# set up shiny js to be able to call our browseURL function
useShinyjs(),
extendShinyjs(text = js_code, functions = 'browseURL'),
# output our wordcloud
wordcloud2Output("my_wc")
)),
server=shinyServer(function(input,output,session){
# create our wordcloud
output$my_wc = renderWordcloud2(wordcloud2(wordcloud_df))
# observe word cloud click event
observeEvent(input$my_wc_clicked, {
# subset url of interest
clicked_word = strsplit(input$my_wc_clicked, ':')[[1]][1]
clicked_url = wordcloud_df$url[wordcloud_df$word == clicked_word]
# navigate to clicked url
js$browseURL(clicked_url)
})
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment