Word cloud Shiny R

Asked

Viewed 328 times

0

I am wanting to make a word cloud using data from a postgresql table. I used an example as a base that I found on the Shiny R site, but I’m not able to do what I want.

I cannot change which variable will serve as the basis of the word cloud. Needed that when renaming the selection in "selectinput" the cloud should also change the variable that is used.

Server.R

function(input, output, session) {
# Define a reactive expression for the document term matrix
terms <- reactive({
# Change when the "update" button is pressed...
input$update
# ...but not for anything else
isolate({
  withProgress({
    setProgress(message = "Processing corpus...")
    getTermMatrix(input$selection)
  })
})
})

# Make the wordcloud drawing predictable during a session
wordcloud_rep <- repeatable(wordcloud)

output$plot <- renderPlot({
v <- terms()
wordcloud_rep(names(v), v, scale=c(4,0.5),
              min.freq = input$freq, max.words=input$max,
              colors=brewer.pal(8, "Dark2"))
})
}

Ui.R
fluidPage(
# Application title
titlePanel("Word Cloud"),

sidebarLayout(
# Sidebar with a slider and selection inputs
sidebarPanel(
  selectInput("selection", "Choose a book:",
              choices = c("Forzza","Viana")),
  actionButton("update", "Change"),
  hr(),
  sliderInput("freq",
              "Minimum Frequency:",
              min = 1,  max = 1000, value = 1),
  sliderInput("max",
              "Maximum Number of Words:",
              min = 1,  max = 100,  value = 100)
),

# Show Word Cloud
mainPanel(
 tabsetPanel(type = "tabs", 
     tabPanel("Plot", plotOutput("plot"))

)
)
)
)

Global.r
library(tm)
library(wordcloud)
library(memoise)

library(RPostgreSQL)
con <- dbConnect(PostgreSQL(), user="postgres",  password="123456",dbname="postgres")
coletor1=dbGetQuery(con,"SELECT REPLACE(aux_coletprinc,' ','')  aux_coletprinc  from jabot.detacesso2 where aux_coletprinc ilike '%forz%a%'
 limit 10")
coletor2=dbGetQuery(con,"SELECT REPLACE(aux_coletprinc,' ','')    aux_coletprinc  from jabot.detacesso2 where aux_coletprinc ilike '%vian%a%'
 limit 10")

dbDisconnect(con)

books <<- list("Forzza" ,
          "Viana" )


# Using "memoise" to automatically cache the results


getTermMatrix <- memoise(function(book) {
# Careful not to let just any name slip in here; a
# malicious user could manipulate this value.

text <- book    
myCorpus = Corpus(VectorSource(text))
myCorpus = tm_map(myCorpus, content_transformer(tolower))

myDTM = TermDocumentMatrix(myCorpus,
          control = list(minWordLength = 1))

m = as.matrix(myDTM)

sort(rowSums(m), decreasing = TRUE)
  • 1

    You need to change the function getTermMatrix so she can do something with the objects coletor1 and coletor2 depending on any argument from her.

  • Always try to give the community a code that is reproducible. What do we mean by reproducible? That we can copy and paste (crtl + c and crtl + v same) your code on our computer and we will have the same problem you have. If you don’t, we won’t even have how to help you.

1 answer

2

Your code has many problems. Below is a generic solution to the problem you described in the question: interactivity of the word cloud.

As you reported no problems with reading the data I isolated the functions of the RPostgreSQL and created "fantasy books". All you’ll need to do is swap the object books for something like books <<- list(coletor1, coletor2).

library(tm)
library(wordcloud)
library(memoise)
library(shiny)
library(stringr)

books <- list(Forzza = c("Um", "monte", "de", "palavras"),
              Viana = c("Outro", "texto", "vai", "aqui", "palavras"))

getTermMatrix <- memoise(function(text) {
  myCorpus = Corpus(VectorSource(text))
  myCorpus = tm_map(myCorpus, content_transformer(tolower))

  myDTM = TermDocumentMatrix(myCorpus,
                             control = list(minWordLength = 1))

  m = as.matrix(myDTM)

  sort(rowSums(m), decreasing = TRUE)
})

server <- shinyServer(function(input, output, session) {
    terms <- reactive({
      input$update
      isolate({
        withProgress({
          setProgress(message = "Processing corpus...")
          getTermMatrix(books[[input$selection]])
        })
      })
    })

    wordcloud_rep <- repeatable(wordcloud)

    output$plot <- renderPlot({
      v <- terms()
      wordcloud_rep(names(v), v, scale=c(4,0.5),
                    min.freq = input$freq, max.words=input$max,
                    colors=brewer.pal(8, "Dark2"))
    })
})

ui <- shinyUI(fluidPage(
  titlePanel("Word Cloud"),

  sidebarLayout(
    sidebarPanel(
      selectInput("selection", "Choose a book:",
                  choices = c("Forzza","Viana")),
      actionButton("update", "Change"),
      hr(),
      sliderInput("freq",
                  "Minimum Frequency:",
                  min = 1,  max = 1000, value = 1),
      sliderInput("max",
                  "Maximum Number of Words:",
                  min = 1,  max = 100,  value = 100)
    ),

    mainPanel(
      tabsetPanel(type = "tabs", 
                  tabPanel("Plot", plotOutput("plot"))

      )
    )
  )
))

shinyApp(ui = ui, server = server)
  • Man, I really appreciate it. You have no idea how much you’ve helped me.I’m in my senior year of college, close to presenting my TCC, and Shiny was the last detail I needed to finish.Thank you very much indeed.

  • About the problems of code, there really are many, because I tried to adapt from another code to this one. There is actually a reading problem, which in my case needed to read each word being a field (line) of the table that is in the variables collector1 and collector2, because he was not seeing compound names, only word for word. But the main one you already helped me. But this last problem I can try to solve here. But thanks even for the help.

  • I suggest you ask another question isolating the problem you are having with reading the data. Take a look at this article. We want to help you, but we have to have.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.