R 当用户按下';输入';,带着反应的表情

R 当用户按下';输入';,带着反应的表情,r,twitter,shiny,analysis,reactive,R,Twitter,Shiny,Analysis,Reactive,这是一个使用Twitter的API分析推文的应用程序 有一个textInput,当前每次输入更改时,服务器都会提取数据、清理数据并更新绘图。 我只希望在用户键入搜索词,然后按“回车”后发生这种情况 我相信这可以用isolate()完成,但我不知所措。 非常感谢您的帮助,谢谢 我目前有一个tag$脚本,在上次用户按键时读取。在测试时,当我按enter键时,初始图形会显示出来,但是,无论何时我在之后更新文本字段,绘图都会更新,而无需按enter键。不知道为什么,因为我在observe()中有代码,但

这是一个使用Twitter的API分析推文的应用程序 有一个textInput,当前每次输入更改时,服务器都会提取数据、清理数据并更新绘图。 我只希望在用户键入搜索词,然后按“回车”后发生这种情况

我相信这可以用isolate()完成,但我不知所措。 非常感谢您的帮助,谢谢

我目前有一个tag$脚本,在上次用户按键时读取。在测试时,当我按enter键时,初始图形会显示出来,但是,无论何时我在之后更新文本字段,绘图都会更新,而无需按enter键。不知道为什么,因为我在observe()中有代码,但我一定是理解错了。代码如下,但如果没有自己的Twitter API密钥,您无法完全运行它

library(shiny)
library(ggplot2)
library(readr)
library(rsconnect) # Deploy Shiny App
library(data.table)
library(plotly)
library(tm) # Text mining
library(dplyr)
library(twitteR) # Pull from Twitter API
library(sentimentr) # Sentiment Analysis
library(tidytext)
library(Unicode)
library(RColorBrewer) # Color palletes
library(base64enc)
library(shinyWidgets) 
library(shinycssloaders) # Loading animatiions
library(wordcloud) # Create wordclouds
library(shinyjs) # Calls shinyjs functions

ui <- fluidPage(

  tags$script(' $(document).on("keydown", function (e) {
                                                 Shiny.onInputChange("lastkeypresscode", e.keyCode);
                                                  });'),
fluidRow( 
    column(12,
           h2("Show me analysis on")),
           textInput("search","", value = "cats")),

    )
  ),
fluidRow(
    column(6, plotOutput("wordcloud") %>% withSpinner()),
    column(6, plotlyOutput("sentiment")  %>% withSpinner()

    )
  )

)

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

  # Authentication keys to access TWitter's API
  consumerKey <- 'k1WaBd'
  consumerSecret <- 'XFQMKfh'
  accessToken <- '14554'
  accessSecret <- 'ZHDvhGmdh'
  setup_twitter_oauth(consumerKey, consumerSecret, accessToken, accessSecret)

# Get Tweet Data
  rawTweets <- reactive({rawTweets <- searchTwitter(req(input$search), n = 200) })

  # Clean raw Twitter data, returns just the body of tweets w/o links and emojis
  cleanTweets <- function(rawTweets){
    df<- do.call("rbind",lapply(rawTweets,as.data.frame))
    # Remove emojis
    df$text <- sapply(df$text,function(row) iconv(row, "latin1", "ASCII", sub="")) 
    df[, c('isRetweet','id', 'longitude','latitude', 'replyToUID', 'replyToSID', 'replyToSN')] <- NULL
    df <- df[!duplicated(df$text), ] # Remove duplicate tweets
    df <- df[!duplicated(df$screenName), ] # Remove duplicate users

    df$text[df$text == ""] <- NA 
    df$letterCount <- nchar(gsub(" ","",df$text)) 
    df$text[df$letterCount == '0'] <- NA 
    df <- na.omit(df)  
    return (df$text)
  }

  # Holds list of cleaned tweets
  words <- reactive({words <- cleanTweets(rawTweets())
  })

  createCorpus <-function(words){

    # Create a corpus to store word data, from package tm
    corpus <- Corpus(VectorSource(words))
    corpus <- tm_map(corpus, removePunctuation)
    corpus <- tm_map(corpus, content_transformer(tolower))
    corpus <- tm_map(corpus,function(x)removeWords(x,stopwords()))

    return(corpus)
  }

  corpus <- reactive({corpus <- createCorpus(words() )})


  observe({
    if(!is.null(input$lastkeypresscode)) {
      if(input$lastkeypresscode == 13){


        if (is.null(input$search) || input$search == "")
          return()

        output$wordcloud <- renderPlot({
          wordcloud(corpus(), min.freq = 3, scale = c(7, 2), random.order = F, colors = brewer.pal(8,'Dark2'))
        })

        # Sentiment Scoring
        sentiment <- reactive({sentiment <- sentiment_by(words()) })
        emotion <- reactive({emotion <- emotion_by(words() )})

        output$sentiment <- renderPlotly({
          # Count # of tweets in each category
          neutral <- sum(sentiment()$ave_sentiment == "0")
          positive <- sum(sentiment()$ave_sentiment > "0")
          negative <- sum(sentiment()$ave_sentiment < "0")
          feeling <- c('positive', 'negative', 'neutral')
          count <- c(positive,negative,neutral)
          df <- data.frame(feeling,count, stringsAsFactors=FALSE)

          plot_ly(df,labels = ~feeling, values = ~count, type = 'pie', 
                  marker = list(colors = c('#c2fa87', '#ffb39c', '#d1d1c9'))
        })


      }
    }
  })

}

shinyApp(ui = ui, server = server)
库(闪亮)
图书馆(GG2)
图书馆(readr)
库(rsconnect)#部署闪亮应用程序
库(数据表)
图书馆(绘本)
图书馆(tm)#文本挖掘
图书馆(dplyr)
库(twitteR)#从twitteR API中提取
图书馆(感伤者)#感伤分析
图书馆(tidytext)
库(Unicode)
图书馆(彩盒)#彩色托盘
图书馆(base64enc)
图书馆(shinyWidgets)
图书馆(shinycssloaders)#加载动画
图书馆(wordcloud)#创建wordclouds
库(shinyjs)#调用shinyjs函数
ui%withSpinner()),
列(6,plotlyOutput(“情绪”)%%>%withSpinner()
)
)
)

服务器我尚未正确测试,但您可以尝试使用observeEvent而不是observe,如下所示:

observeEvent(req(input$lastkeypresscode==13), {

    if (is.null(input$search) || input$search == "")
      return()

    output$wordcloud <- renderPlot({
      wordcloud(corpus(), min.freq = 3, scale = c(7, 2), random.order = F, colors = brewer.pal(8,'Dark2'))
    })

    # Sentiment Scoring
    sentiment <- reactive({sentiment <- sentiment_by(words()) })
    emotion <- reactive({emotion <- emotion_by(words() )})

    output$sentiment <- renderPlotly({
      # Count # of tweets in each category
      neutral <- sum(sentiment()$ave_sentiment == "0")
      positive <- sum(sentiment()$ave_sentiment > "0")
      negative <- sum(sentiment()$ave_sentiment < "0")
      feeling <- c('positive', 'negative', 'neutral')
      count <- c(positive,negative,neutral)
      df <- data.frame(feeling,count, stringsAsFactors=FALSE)

      plot_ly(df,labels = ~feeling, values = ~count, type = 'pie', 
              marker = list(colors = c('#c2fa87', '#ffb39c', '#d1d1c9'))
    })
})
observeEvent(请求(输入$lastkeypresscode==13){
if(is.null(输入$search)| |输入$search==“”)
返回()

输出$wordcloud我尝试使用搜索操作按钮

ui <- fluidPage(
  fluidRow(column(6,
                  h2("Show me analysis on")),
           textInput("keySearch", NULL)),
  column(
    width = 1,
    actionButton("search", "Search"),
    tags$style(
      "#search { color: #fff; background-color: #00557F; margin-top:24px; font-family: 'Candara'; }"
    )
  ),
  fluidRow(
    column(6, plotOutput("wordcloud") %>% withSpinner()),
    column(6, plotlyOutput("sentiment")  %>% withSpinner())
  )
)

server <- function(input, output, session) {
  # Authentication keys to access TWitter's API
  consumerKey <- 'your key'
  consumerSecret <- 'your secret'
  accessToken <- 'your token'
  accessSecret <- 'your secret'
  setup_twitter_oauth(consumerKey, consumerSecret, accessToken, accessSecret)

  # Get Tweet Data
  rawTweets <-
    eventReactive(input$search, {
      searchTwitter(req(input$keySearch), n = 200)
    })

  # Clean raw Twitter data, returns just the body of tweets w/o links and emojis
  cleanTweets <- function(rawTweet) {
    df <- do.call("rbind", lapply(rawTweet, as.data.frame))
    # Remove emojis
    df$text <-
      sapply(df$text, function(row)
        iconv(row, "latin1", "ASCII", sub = ""))
    df[, c(
      'isRetweet',
      'id',
      'longitude',
      'latitude',
      'replyToUID',
      'replyToSID',
      'replyToSN'
    )] <- NULL
    df <- df[!duplicated(df$text),] # Remove duplicate tweets
    df <- df[!duplicated(df$screenName),] # Remove duplicate users

    df$text[df$text == ""] <- NA
    df$letterCount <- nchar(gsub(" ", "", df$text))
    df$text[df$letterCount == '0'] <- NA
    df <- na.omit(df)
    return (df$text)
  }

  # Holds list of cleaned tweets
  words <- reactive({
    words <- cleanTweets(rawTweets())
  })

  createCorpus <- function(words) {
    # Create a corpus to store word data, from package tm
    corpus <- Corpus(VectorSource(words))
    corpus <- tm_map(corpus, removePunctuation)
    corpus <- tm_map(corpus, content_transformer(tolower))
    corpus <- tm_map(corpus, function(x)
      removeWords(x, stopwords()))

    return(corpus)
  }

  corpus <- reactive({
    corpus <- createCorpus(words())
  })


  observeEvent(input$search, {
    output$wordcloud <- renderPlot({
      wordcloud(
        corpus(),
        min.freq = 3,
        scale = c(7, 2),
        random.order = F,
        colors = brewer.pal(8, 'Dark2')
      )
    })

    # Sentiment Scoring
    sentiment <- reactive({
      sentiment <- sentiment_by(words())
    })
    emotion <- reactive({
      emotion <- emotion_by(words())
    })

    output$sentiment <- renderPlotly({
      # Count # of tweets in each category
      neutral <- sum(sentiment()$ave_sentiment == "0")
      positive <- sum(sentiment()$ave_sentiment > "0")
      negative <- sum(sentiment()$ave_sentiment < "0")
      feeling <- c('positive', 'negative', 'neutral')
      count <- c(positive, negative, neutral)
      df <- data.frame(feeling, count, stringsAsFactors = FALSE)

      plot_ly(
        df,
        labels = ~ feeling,
        values = ~ count,
        type = 'pie',
        marker = list(colors = c('#c2fa87', '#ffb39c', '#d1d1c9'))
      )
    })
  })

}

shinyApp(ui = ui, server = server)
ui%withSpinner()),
列(6,plotlyOutput(“情绪”)%%>%withSpinner())
)
)

服务器我不确定“输入按钮按更新”,但您是否可以使用带有EventResponsive的,以便仅当用户按下actionbutton时程序才会更新?observeEvent专门关注列出的事件,而observe对其中任何反应值的更改作出反应。另一个选项是使用isolate,但我认为这更简洁。另外,最好使用Responsive在observeEvent之外。这也可能有帮助。还应该将
shinniputchange(“lastkeypresscode”,e.keyCode)
替换为
shinniputValue(“lastkeypresscode”,e.keyCode,{priority:“event”})
。基本上,我将actionButton与EventResponsive和observeEvent结合使用,仅当按下按钮时才产生输出。我测试了代码,它运行良好。