Я пытаюсь отобразить 50 наиболее часто используемых терминов в формате wordcloud. Я полагаю, что мне чего-то не хватает в коде сервера

#r

Вопрос:

Я пытаюсь отобразить 50 наиболее часто встречающихся слов со страниц, извлеченных из Википедии. Я думаю, что правильно настроил часть wordcloud. У меня возникли проблемы с поиском правильного способа визуализации на стороне сервера. Мне просто использовать функцию renderWordcloud или просто построить график?

Это мой код пользовательского интерфейса

 library(shiny)
titles <- c("Web_analytics","Text_mining","Integral", "Calculus", 
            "Lists_of_integrals", "Derivative","Alternating_series",
            "Pablo_Picasso","Vincent_van_Gogh","Leo_Tolstoy","Web_crawler")
# Define UI for application 
shinyUI(fluidPage(
  # Application title (Panel 1)
  titlePanel("Wiki Pages"), 
  # Widget (Panel 2) 
  sidebarLayout(
    sidebarPanel(h3("Search panel"),
                 # Where to search 
                 selectInput("select",
                             label = h5("Choose from the following Wiki Pages on"),
                             choices = titles,
                             selected = titles, multiple = TRUE),
                 textInput(inputId = "txt",
                           label = h5("Add Search Terms")),
                 # Start Search
                 submitButton("Results")
    ),
    # Display Panel (Panel 3)
    mainPanel(                   
      h1("Display Panel",align = "center"),
      plotOutput("plot")
    )
  )
))
 

Это мой серверный код:

 library(shiny)
library(tm)
# library(stringi)
# library(proxy)
source("WikiSearch.R")

shinyServer(function(input, output) {
  output$plot <- renderPlot({ 
    
    # Progress Bar while executing function
    withProgress({
      setProgress(message = "Mining Wikipedia ...")
      result <- SearchWiki(input$select)
    })
    
    plot(result, labels = input$select, sub = "",main="Wikipedia Search")
  })
})
 

Это исходный код, который извлекается из.

 library(tm)
library(stringi)
library(WikipediR)
library(wordcloud)

SearchWiki <- function (titles) {
  articles <- lapply(titles,function(i) page_content("en","wikipedia", page_name = i,as_wikitext=TRUE)$parse$wikitext)
  
  docs <- VCorpus(VectorSource(articles)) # Get Web Pages' Corpus
  remove(articles)
  
  # Text analysis - Preprocessing 
  transform.words <- content_transformer(function(x, from, to) gsub(from, to, x))
  temp <- tm_map(docs, transform.words, "<. ?>", " ")
  temp <- tm_map(temp, transform.words, "t", " ")
  temp <- tm_map(temp, content_transformer(tolower)) # Conversion to Lowercase
  temp <- tm_map(temp, PlainTextDocument)
  temp <- tm_map(temp, stripWhitespace)
  temp <- tm_map(temp, removeWords, stopwords("english"))
  temp <- tm_map(temp, removePunctuation)
  temp <- tm_map(temp, stemDocument, language = "english") # Perform Stemming
  remove(docs)
  
  # Create Dtm 
  dtm <- DocumentTermMatrix(temp)
  dtm <- removeSparseTerms(dtm, 0.4)
  m <- as.matrix(dtm)
  v <- head(sort(rowSums(m), decreasing = TRUE),n = 50)
  dFcloud <- data.frame(word = names(v), freq = as.numeric(v))
  
  #Generate the wordcloud
  set.seed(2324)
  wordcloud(words = dFcloud$word,freq = dFcloud$freq, min.freq = 50)
}
 

Ответ №1:

Выстрел в темноте: Это работает?

 shinyServer(function(input, output) {
  output$plot <- renderPlot({ 
    
    # Progress Bar while executing function
    withProgress({
      setProgress(message = "Mining Wikipedia ...")
      SearchWiki(input$select)
    })
  })
})
 

Мне кажется, что тот SearchWiki ничего не возвращает и строит планы сразу. Однако я не уверен, что withProgress это все испортит.

Если нет, попробуйте обойтись без индикатора выполнения:

 shinyServer(function(input, output) {
  output$plot <- renderPlot({ 
    
    # Progress Bar while executing function
    SearchWiki(input$select)
  })
})
 

Если это работает, но не выше, вам нужно изменить перемещение линии построения из SerachWiki исходного кода и в исходный код.

Комментарии:

1. Привет, Андерс, это частично сработало. Он действительно создал wordcloud, но я получаю только символ(0) в wordcloud. Это может быть связано с сортировкой, которая у меня есть.

2. Тогда, похоже, возникли проблемы с SearchWiki. Можете ли вы привести мне пример того, как использовать SearchWiki и создавать wordcloud без shiny?