server.R манипулирование данными и зависимые события, множество проблем - PullRequest
0 голосов
/ 08 июня 2019

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

enter image description here

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

Мои проблемы заключаются в следующем:

  1. updateSliderInput (не обновляет значения)

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

Код, который я написал с небольшим воспроизводимым фиктивным набором данных, включен ниже:


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


# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  #titlePanel("Twitter Analytics"),

  fluidRow( 
    column( 4, titlePanel("Twitter Analytics")),
    column( 3),#, textOutput("mysearch") ),
    column( 4,            #tags$script(
            # '$(document).on("keydown", function (e) {
            #  Shiny.onInputChange("lastkeypresscode", e.keyCode);
            #  });'),
            #p("enter Search Term"),
            textInput("searchstring", 
                      label = "",
                      value = "")),
    column(1, 
           br(),
           actionButton("action", "go"))


    # submitButton("search tweets")
    # textInput2("textinput", "Enter text:")

  ),

  fluidRow( 

    column( 12, tabsetPanel(
      tabPanel("one",
               fluidRow(
                 column(3,
                        fluidRow(
                          column(11, offset = 1, 
                                 br(),
                                 p("It is often necessary to remove words that dont make sence in the corpus" ),
                                 textInput("remove", 
                                           label = "remove word",
                                           value = ""),

                                 p(" there may also be spelling mistakes, or pluralisations that you want to remove
                                   , a use full hint it to replace the pluralised word with the shortened form i.e. words replace with word"),
                                 textInput("find", 
                                           label = "find word",
                                           value = ""),
                                 textInput("replace", 
                                           label = "replace word",
                                           value = ""), 
                                 checkboxGroupInput("checkGroup", "select plots",
                                                    choices <- c("Histogram", "Wordcloud", "network")),
                                 sliderInput("topTerms",
                                             label = "top (n) terms", 
                                             min = 0, max = 25, value = 0)
                                 )
                 )

                 ),
                 column(9, fluidRow(column(12, plotOutput("ttext"))),
                        fluidRow(column(12,wordcloud2Output("wc2"))))
                 )
    ),


    tabPanel("two"),
    tabPanel("three"), 
    tabPanel("DataTable",
             fluidRow(
               column(12, dataTableOutput("mysearch") )
             )
    )
    )
    )
)
  )





server <- function(input, output, session) {

  twitter <- eventReactive(input$action,{
    #st <- search_tweets( input$searchstring , n = 500, include_rts = FALSE)
    #st <- as.data.frame(st)
    # this a dummy data frame
      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)
  })

  cleanset <- eventReactive(input$action,{
    df <- twitter()
    df<- data.frame(doc_id=row.names(df),
                    text=df$text)
    #df<- as.data.frame(df)
    df$text = tolower(df$text)
    # Replace @UserName
    df$text <- gsub("@\\w+", "", df$text)
    #remove punctuation
    df$text <- gsub("[[:punct:]]", "", df$text)
    #remove links
    df$text <- gsub("http\\w+", "", df$text)
    # Remove tabs
    df$text <- gsub("[ |\t]{2,}", "", df$text)
    # Remove blank spaces at the beginning
    df$text <- gsub("^ ", "", df$text)
    # Remove blank spaces at the end
    df$text <- gsub(" $", "", df$text)
    corpus <- iconv(df$text, to = "ASCII")
    #corpus <- as.data.frame(corpus)
    corpus <- Corpus(VectorSource(corpus))
    corpus <- tm_map(corpus, removePunctuation)

    corpus <- tm_map(corpus, removeNumbers)

    cleanset <- tm_map(corpus, removeWords, stopwords('english'))
    cleanset <- tm_map(cleanset, removeWords, c(input$searchstring))
    cleanset <- tm_map(cleanset, stripWhitespace)
    #  tdm <- TermDocumentMatrix(cleanset)
    #  tdm <- as.matrix(tdm)
    #  w <- rowSums(tdm)
  })

  docMatrix <- eventReactive(input$action,{
    cleanset <- cleanset()
    tdm <- TermDocumentMatrix(cleanset)
    tdm <- as.matrix(tdm)
    w <- rowSums(tdm)
  })
  observe({input$action
    w <- docMatrix()
    maxW = max(w)
    updateSliderInput(session, "topTerms", min = min(w), max = maxW, value = min(w))
  })

Я был бы признателен за любую помощь, которую кто-то мог бы предложить мнеЯ считаю, что проблема заключается в том, как я манипулирую данными в разделе сервера

...