Обработка данных о реактивном событии - PullRequest
0 голосов
/ 08 июня 2019

Я создаю фрейм данных, который динамически создается, когда пользователь вводит поисковый запрос, для этого у меня есть кнопка действия, а фрейм данных создается при нажатии кнопки «Перейти».

Как только это будет сделано, мне нужно выполнить различные манипуляции с данными на DF и вывести различные графики.

Я пытаюсь понять, как я выполняю манипуляции с данными в Shiny, у меня есть несколько упрощенных примеров.код ниже:

library(shiny)
library(sp)
library(stringr)
library(tidyr)
library(tidyverse)
library(tm)
library(ggplot2)
library(stringi)
library(plyr)
library(dplyr) 

ui <- fluidPage(

  fluidRow( 
    column( 4, titlePanel("Twitter Analytics")),
    column( 3),
    column( 4, 
            textInput("searchstring", 
                      label = "",
                      value = "")),
    column(1, 
           br(),
           actionButton("action", "go"))
  ),
  fluidRow(
    column( 12, tabsetPanel(
      tabPanel("one",
               fluidRow(
                 column(3 ),
                 column(9,  plotOutput("ttext"))
               )
      ),    
      tabPanel("two"),
      tabPanel("three")
    )
    )
  )
)

server <- function(input, output) {

  tweet <- eventReactive(input$action,{
    num <- c(1,2,3,4,50)
    text <- c("this is love love something", "this is not hate hate hate something", "@something islove  rethched this not", " Shiny is love confusing me", "this is hate also somthing difficult")
    letter<- c("a", "b", "c", "D", "e")
    tweetdf <- data.frame(num, text, letter)
  })

  tdm <- if( is.null(tweetdf) ){return()}
  else{
    tweetdf$text <- tolower(tweetdf$text)
    # tweetdf @UserName
    tweetdf$text <- gsub("@\\w+", "", tweetdf$text)
    #remove punctuation
    tweetdf$text <- gsub("[[:punct:]]", "", tweetdf$text)
    #remove links
    tweetdf$text <- gsub("http\\w+", "", tweetdf$text)
    # Remove tabs
    tweetdf$text <- gsub("[ |\t]{2,}", "", tweetdf$text)
    # Remove blank spaces at the beginning
    tweetdf$text <- gsub("^ ", "", tweetdf$text)
    # Remove blank spaces at the end
    corpus <- iconv(tweetdf$text, to = "ASCII")
    corpus <- Corpus(VectorSource(corpus))
    corpus <- tm_map(corpus, removePunctuation)
    corpus <- tm_map(corpus, removeNumbers)
    cleanset <- tm_map(corpus, removeWords, stopwords('english'))
    tdm <- TermDocumentMatrix(cleanset)
    tdm <- as.matrix(tdm)
    w <- rowSums(tdm)
  }

    output$ttext <- renderPlot({ 
        library(RColorBrewer)
        barplot(w)

    })
    output$wordCl <- renderPlot({
      library(wordcloud2)
      w <- data.frame(names(w), w)
      colnames(w) <- c('word', 'freq')
      wordcloud2(w,
                 color = 'random-dark',
                 size = 0.7,
                 shape = 'circle',
                 rotateRatio = 0.5,
                 minSize = 1)
    })
  }

  shinyApp(ui, server)

я продолжаю получать сообщение об ошибке, что tweetdf не существует, его не должно быть, пока пользователь не введет поисковый запрос и не нажмет "go"

Что такоелучший способ решить эту проблему, это даже правильное место, чтобы сделать это

1 Ответ

0 голосов
/ 08 июня 2019

Он сообщает вам, что твит tweetdf не существует, потому что результат eventReactive (tweetdf) присваивается переменной tweet, что делает твит вашей фактической реактивной переменной с результатом tweetdf in.

Также проблема в вашем коде состоит в том, что вы смешиваете классические переменные с реактивными переменными.

Вы можете получить доступ к реактивным переменным, добавив скобки в конце переменной ()

Вот рабочий пример:

library(shiny)
library(sp)
library(stringr)
library(tidyr)
library(tidyverse)
library(tm)
library(ggplot2)
library(stringi)
library(plyr)
library(dplyr) 
library(RColorBrewer)
library(wordcloud2)

ui <- fluidPage(

  fluidRow( 
    column( 4, titlePanel("Twitter Analytics")),
    column( 3),
    column( 4, 
            textInput("searchstring", 
                      label = "",
                      value = "")),
    column(1, 
           br(),
           actionButton("action", "go"))
  ),
  fluidRow(
    column( 12, tabsetPanel(
      tabPanel("one",
               fluidRow(
                 column(3 ),
                 column(9,  plotOutput("ttext"))
               )
               # ,fluidRow(wordcloud2Output("wordCl"))
      ),    
      tabPanel("two"),
      tabPanel("three")
    )
    )
  )
)

server <- function(input, output) {

  w <- eventReactive(input$action,{
    num <- c(1,2,3,4,50)
    text <- c("this is love love something", "this is not hate hate hate something", "@something islove  rethched this not", " Shiny is love confusing me", "this is hate also somthing difficult")
    letter<- c("a", "b", "c", "D", "e")
    tweetdf <- data.frame(num, text, letter)

    tdm <- if( is.null(tweetdf) ){return()} ## should not use return here as this is not a function
    else{
      print(tweetdf)
      tweetdf$text <- tolower(tweetdf$text)
      # tweetdf @UserName
      tweetdf$text <- gsub("@\\w+", "", tweetdf$text)
      #remove punctuation
      tweetdf$text <- gsub("[[:punct:]]", "", tweetdf$text)
      #remove links
      tweetdf$text <- gsub("http\\w+", "", tweetdf$text)
      # Remove tabs
      tweetdf$text <- gsub("[ |\t]{2,}", "", tweetdf$text)
      # Remove blank spaces at the beginning
      tweetdf$text <- gsub("^ ", "", tweetdf$text)
      # Remove blank spaces at the end
      corpus <- iconv(tweetdf$text, to = "ASCII")
      corpus <- Corpus(VectorSource(corpus))
      corpus <- tm_map(corpus, removePunctuation)
      corpus <- tm_map(corpus, removeNumbers)
      cleanset <- tm_map(corpus, removeWords, stopwords('english'))
      tdm <- TermDocumentMatrix(cleanset)
      tdm <- as.matrix(tdm)
      w <- rowSums(tdm)
    }

  })

  output$ttext <- renderPlot({ 
    barplot(w())
  })


  output$wordCl <- renderWordcloud2({
    w <- data.frame(names(w()), w())

    colnames(w) <- c('word', 'freq')

    wordcloud2(w,
               color = 'random-dark',
               size = 0.7,
               shape = 'circle',
               rotateRatio = 0.5,
               minSize = 1)
  })
}

shinyApp(ui, server)

...