can't visualize output in schiny dashboard

Good morning, I have problems with a schiny dashboard for a university project. When I start the app it returns the following error "arguments imply differing number of rows: 0.1". Error that repeats for each output. I can't understand what I did wrong. I am attaching two scripts to the topic: in "global" you find the test datasets and the function to obtain the dtm; in "ui_server" instead the user interface and server is present. I tested the dtm function off the dashboard and it works. I think the problem is in the selection of the input dataframe. I read guides and documentation but nothing ... I can't understand where the error is, also because everything seems in line with the indications provided by the documentation.

df1=as.data.frame(cbind(userid=c(1:10), created_at=c(seq(as.Date("2000/1/1"),by= "month", length.out = 10)), 
                    text= c("Abuso sessuale e aggravante dell'uso di sostanze alcoliche", 
                            "Per chi non ricordasse, con l'attuale legge l'accusa di stupro si può avanzare solamente qualora si possa provare la presenza di violenza. Se la vittima reagisce in modo passivo, senza opporre evidente resistenza, non sussiste stupro, ma abuso sessuale. Insomma, un abominio.", 
                            "@BarbaraDeRossiO Al netto dei titoli sensazionalistici, la CdC ha evidenziato che c'è stata violenza sessuale di gruppo con abuso delle condizioni di inferiorità psichica o fisica.  Non ha detto non c'è stato stupro perché la vittima si era ubriacata o la colpa è tua perché avevi bevuto", 
                            "@FiorellaMannoia Cara Fiorella, cito da una mia amica:",
                            "In Manitoba, 6 women were killed",
                            "@FiorellaMannoia Cara Fiorella, cito da una mia amica:", 
                            "@PiovonoRoseNere @Giudo621 Non è così .. lo stupro è stato riconosciuto. non è stata riconosciuta l'aggravante dell'uso di sostanze alcoliche .. ma la violenza sessuale con l'aggravante dell'abuso di inferiorità psichica proprio perche era ubriaca è stato confermato.",
                            "#violenzasessusle #cassazione prima che vi scannia",
                            "@Manu_Erre_ Il punto che è un reato specifico, la ",
                            "Si sta scatenando un vortice insulso sulla sentenza")))
df2=as.data.frame(cbind(userid=c(1:7), created_at=c(seq(as.Date("2000/1/1"),by= "month", length.out = 7)), 
                    text= c("@DanielaPF75 @laura_lavespa @chiara84 Se ho ca", 
                            "@salvodimartino6 violenza sessuale di gruppo con abuso condizioni di inferiorità psichica o fisica anche se la vittima ha assunto alcol volontariamente, visto che in uno stato in infermit psichica a prescindere da chi l'abbia determinato,mancano le condizioni per prestare un valido consenso", 
                            "@1511maxi @MustErminea Ascoltami, per tua fortuna", 
                            "La Cassazione (sent. 32462 della III sez. penale) ha ",
                            "Dato che se parla ma nessuno spiega, no, non siamo",
                            "Il reato di violenza sessuale di gruppo con abuso de", 
                            "Quando sale la paura che nostro figlio autistico sia"
                    )))
df3=as.data.frame(cbind(userid=c(1:7), created_at=c(seq(as.Date("2000/1/1"),by= "month", length.out = 7)), 
                    text= c("Abuso sessuale e dinamiche familiari Spesso il luogo", 
                            "Abuso sessuale su una signora cinquantenne durante", 
                            "Ma come fatte a dire che la pedofilia è un orientameto", 
                            "Spagna, ragazza violentata da 5 persone. ",
                            "Carica di abuso sessuale di OSU mette in chiaro:",
                            "Perché non digiunate 10 giorni per ogni abuso sessua", 
                            "La Spagna introduce legge sul consenso esplicito"
                    )))  

datasets<<- list("first dataframe"="df1", 
             "second dataframe"="df2", 
             "third dataframe"="df3" 
             )

getTermMatrix <- memoise(function(dataset) {
users <- dataset[1]
text <- dataset[3]
df_title <- data.frame(doc_id= row.names(users), text= text)
df_title <- remove_empty(df_title, which = "rows")
corpus <- Corpus(DataframeSource(df_title))
removeap <- function(x) gsub("'", " ", x)
removeNumPunct <- function(x) gsub("[^[:alpha:][:space:][:cntrl:][:alnum:][:blank:]?&/\\-]*", "", x)
removeURL <- function(x) gsub(" ?(f, ht)(tp)(s?)(://)(.*)[., /](.*)", "", x)
removeshorturl <- function(x) gsub("[goo.\\S+][@\\S+][ow.ly\\S+][ow.ly\\S+][bit.ly\\S+][fb.\\S+]
                               [pic.\\S+][\\S+\\.it\\S+][\\S+\\.com\\S+]", "", x)
corpus=tm_map(corpus, content_transformer(removeap))
corpus=tm_map(corpus, content_transformer(removeURL))
corpus=tm_map(corpus, content_transformer(removeshorturl))
corpus=tm_map(corpus, content_transformer(removeNumPunct))
corpus=tm_map(corpus, removeWords, stopwords("it"))
ds0 <- tm_map(corpus,content_transformer(tolower))
ds1 <- tm_map(ds0,removeNumbers)
ds <- tm_map(ds1, removeWords, c ("nulla", "pare", "niente", "nessuno", "nessuna", "meno", "https", "cosÃ", "giÃ", "enne"))
dtm <- DocumentTermMatrix(ds, control = list(removePunctuation = TRUE, stopwords = "it"))
})

UI and SERVER


ui <- fluidPage(titlePanel("IULM Dashboard"), sidebarLayout(sidebarPanel(
selectInput("dataset", "Choose a Dataset:",
          choices = datasets), actionButton("update", "Change")

)   
,

mainPanel(  
plotOutput(outputId = "wordcloud", width = 600, height = 600),
tableOutput(outputId = "latenttopics")
)   
)   
)

server <- function(input, output){

datasetInput <- reactive({

input$update

isolate({
  withProgress({
    setProgress(message = "Processing corpus...")
    getTermMatrix(input$dataset)
  })
  })
  })

output$wordcloud <- renderPlot({
v=datasetInput()
dtm1 = removeSparseTerms(v, 0.992)
rowTotals <- apply(dtm1 , 1, sum) 
dtm2   <- dtm1[rowTotals> 0, ]
wdtm <- weightTf(dtm2)
freq <- colSums(as.matrix(wdtm))
wf = data.frame(term = names(freq), occurrences = freq)
wc <- as.matrix(weightTf(wf[1]))
wordcloud(wc, freq = wf$occurrences, max.words= 50, scale = c(10,1), random.color= TRUE, random.order= FALSE, 
          rot.per= 0.35, colors= brewer.pal(8, "Dark2"))
 })



output$latenttopics <- renderTable({
v=datasetInput()
burnin <- 4000
iter <- 2000
thin <- 500
seed <-list(2003,5,63,100001,765)
nstart <- 5
best <- TRUE
k <- 5
dtm1 = removeSparseTerms(v, 0.992)
rowTotals <- apply(dtm1 , 1, sum) 
dtm2   <- dtm1[rowTotals> 0, ]
ldaOut <- LDA(dtm2, k=k, method= "Gibbs")
ldaOut.terms.top10 <- as.data.frame(terms(ldaOut,10))
ldaOut.terms.top10}

)

}


shinyApp(ui = ui, server = server)

Hi @rccmazza90. Your question is not clear and didn't mention the packages that you used. This will be make the question more complicated.
You code have not much error. Just the datasets didn't pass correctly to the getTermMatrix. I made some changes there and the input$dataset. Hope can help.

library(tidyverse)
library(shiny)

df1=as.data.frame(cbind(userid=c(1:10), created_at=c(seq(as.Date("2000/1/1"),by= "month", length.out = 10)), 
                        text= c("Abuso sessuale e aggravante dell'uso di sostanze alcoliche", 
                                "Per chi non ricordasse, con l'attuale legge l'accusa di stupro si può avanzare solamente qualora si possa provare la presenza di violenza. Se la vittima reagisce in modo passivo, senza opporre evidente resistenza, non sussiste stupro, ma abuso sessuale. Insomma, un abominio.", 
                                "@BarbaraDeRossiO Al netto dei titoli sensazionalistici, la CdC ha evidenziato che c'è stata violenza sessuale di gruppo con abuso delle condizioni di inferiorità psichica o fisica.  Non ha detto non c'è stato stupro perché la vittima si era ubriacata o la colpa è tua perché avevi bevuto", 
                                "@FiorellaMannoia Cara Fiorella, cito da una mia amica:",
                                "In Manitoba, 6 women were killed",
                                "@FiorellaMannoia Cara Fiorella, cito da una mia amica:", 
                                "@PiovonoRoseNere @Giudo621 Non è così .. lo stupro è stato riconosciuto. non è stata riconosciuta l'aggravante dell'uso di sostanze alcoliche .. ma la violenza sessuale con l'aggravante dell'abuso di inferiorità psichica proprio perche era ubriaca è stato confermato.",
                                "#violenzasessusle #cassazione prima che vi scannia",
                                "@Manu_Erre_ Il punto che è un reato specifico, la ",
                                "Si sta scatenando un vortice insulso sulla sentenza")))

df2=as.data.frame(cbind(userid=c(1:7), created_at=c(seq(as.Date("2000/1/1"),by= "month", length.out = 7)), 
                        text= c("@DanielaPF75 @laura_lavespa @chiara84 Se ho ca", 
                                "@salvodimartino6 violenza sessuale di gruppo con abuso condizioni di inferiorità psichica o fisica anche se la vittima ha assunto alcol volontariamente, visto che in uno stato in infermit psichica a prescindere da chi l'abbia determinato,mancano le condizioni per prestare un valido consenso", 
                                "@1511maxi @MustErminea Ascoltami, per tua fortuna", 
                                "La Cassazione (sent. 32462 della III sez. penale) ha ",
                                "Dato che se parla ma nessuno spiega, no, non siamo",
                                "Il reato di violenza sessuale di gruppo con abuso de", 
                                "Quando sale la paura che nostro figlio autistico sia"
                        )))
df3=as.data.frame(cbind(userid=c(1:7), created_at=c(seq(as.Date("2000/1/1"),by= "month", length.out = 7)), 
                        text= c("Abuso sessuale e dinamiche familiari Spesso il luogo", 
                                "Abuso sessuale su una signora cinquantenne durante", 
                                "Ma come fatte a dire che la pedofilia è un orientameto", 
                                "Spagna, ragazza violentata da 5 persone. ",
                                "Carica di abuso sessuale di OSU mette in chiaro:",
                                "Perché non digiunate 10 giorni per ogni abuso sessua", 
                                "La Spagna introduce legge sul consenso esplicito"
                        )))  

datasets<<- list("first dataframe"=df1, 
                 "second dataframe"=df2, 
                 "third dataframe"=df3 
)

library(tm)

getTermMatrix <- memoise::memoise(function(dataset) {
  dataset <- datasets[[dataset]]
  df_title <- dataset[, c(1,3)]
  df_title <- `colnames<-`(df_title, c("doc_id", "text"))
  df_title <- janitor::remove_empty(df_title, which = "rows")
  corpus <- tm::Corpus(tm::DataframeSource(df_title))
  removeap <- function(x) gsub("'", " ", x)
  removeNumPunct <- function(x) gsub("[^[:alpha:][:space:][:cntrl:][:alnum:][:blank:]?&/\\-]*", "", x)
  removeURL <- function(x) gsub(" ?(f, ht)(tp)(s?)(://)(.*)[., /](.*)", "", x)
  removeshorturl <- function(x) gsub("[goo.\\S+][@\\S+][ow.ly\\S+][ow.ly\\S+][bit.ly\\S+][fb.\\S+]
                               [pic.\\S+][\\S+\\.it\\S+][\\S+\\.com\\S+]", "", x)
  corpus=tm_map(corpus, content_transformer(removeap))
  corpus=tm_map(corpus, content_transformer(removeURL))
  corpus=tm_map(corpus, content_transformer(removeshorturl))
  corpus=tm_map(corpus, content_transformer(removeNumPunct))
  corpus=tm_map(corpus, removeWords, stopwords("it"))
  ds0 <- tm_map(corpus,content_transformer(tolower))
  ds1 <- tm_map(ds0,removeNumbers)
  ds <- tm_map(ds1, removeWords, c ("nulla", "pare", "niente", "nessuno", "nessuna", "meno", "https", "cosÃ", "giÃ", "enne"))
  dtm <- DocumentTermMatrix(ds, control = list(removePunctuation = TRUE, stopwords = "it"))
})

ui <- fluidPage(titlePanel("IULM Dashboard"), sidebarLayout(sidebarPanel(
  selectInput("dataset", "Choose a Dataset:",
              choices = names(datasets)), actionButton("update", "Change")
  
)   
,

mainPanel(  
  plotOutput(outputId = "wordcloud", width = 600, height = 600),
  tableOutput(outputId = "latenttopics")
)   
)   
)

server <- function(input, output){
  
  datasetInput <- reactive({
    
    input$update
    
    isolate({
      withProgress({
        setProgress(message = "Processing corpus...")
        getTermMatrix(input$dataset)
      })
    })
  })
  
  output$wordcloud <- renderPlot({
    v=datasetInput()
    dtm1 = removeSparseTerms(v, 0.992)
    rowTotals <- apply(dtm1 , 1, sum) 
    dtm2   <- dtm1[rowTotals> 0, ]
    wdtm <- weightTf(dtm2)
    freq <- colSums(as.matrix(wdtm))
    wf = data.frame(term = names(freq), occurrences = freq)
    wc <- as.matrix(weightTf(wf[,1]))
    wordcloud::wordcloud(wc, freq = wf$occurrences, max.words= 50, scale = c(10,1), random.color= TRUE, random.order= FALSE, 
              rot.per= 0.35, colors= RColorBrewer::brewer.pal(8, "Dark2"))
  })
  
  output$latenttopics <- renderTable({
    v=datasetInput()
    burnin <- 4000
    iter <- 2000
    thin <- 500
    seed <-list(2003,5,63,100001,765)
    nstart <- 5
    best <- TRUE
    k <- 5
    dtm1 = removeSparseTerms(v, 0.992)
    rowTotals <- apply(dtm1 , 1, sum) 
    dtm2   <- dtm1[rowTotals> 0, ]
    ldaOut <- topicmodels::LDA(dtm2, k=k, method= "Gibbs")
    ldaOut.terms.top10 <- as.data.frame(topicmodels::terms(ldaOut,10))
    ldaOut.terms.top10}
    
  )
  
}


shinyApp(ui = ui, server = server)
#> 
#> Listening on http://127.0.0.1:7618
#> Warning in wordcloud::wordcloud(wc, freq = wf$occurrences, max.words =
#> 50, : aggravante could not be fit on page. It will not be plotted.
#> Warning in wordcloud::wordcloud(wc, freq = wf$occurrences, max.words =
#> 50, : violenza could not be fit on page. It will not be plotted.

Created on 2019-10-14 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.