【问题标题】:Problems with Output, Shiny app R输出问题,Shiny app R
【发布时间】:2015-04-25 03:45:12
【问题描述】:

我正在尝试制作一个 Shiny 应用程序,它允许您在 Twitter 中搜索一个词,然后分析获得的推文的感受并计算正面和负面推文的百分比。我有所有已实现的功能,但我无法在屏幕上写出结果。计算百分比的函数是无效的,也就是说什么都不返回,我该怎么做才能在屏幕上显示结果?

在 ui.r 中:

sidebarPanel(textInput("term", "Put the term",""),
textInput("number","Number of tweets",""), submitButton("Search")),
mainPanel(("Results of the search"),textOutput("result"))

在 server.r 中:

myterm<-reactive({myterm<-TweetFrame(input$term, input$number)})

cleanterms <- reactive({CleanTweets(myterm()["text"])})

sentimentsTweets<-reactive({sentimentsTweets<-sentimentalanalysis(cleanterms()["text"])})

output$result <- renderPrint({paste(print(sentimentsTweets()["score"]))})
output$result <- renderPrint({CalculatePercentaje(as.vector(sentimentsTweets()))})

我希望我知道如何编写显示获得的推文得分以及如何编写调用函数CalculatePercentage的结果,这是函数:

CalculatePercentage<-function(sentimentTweets){

      neutral <- 0
      negativo <- 0
      positivo <- 0

      for(i in 1:length(sentimentTweets$score)){

        if(sentimentTweets$score[i] == 0){
          neutral <- neutral + 1 
        } else {
          if(sentimentTweets$score[i] > 0){
            positivo <- positivo + 1
          } else {
            negativo <- negativo + 1
          }
        }

      }

      cat("El porcentaje de tweets neutrales es ", (neutral * 100)/ length(sentimentTweets$score), "% \n")
      cat("El porcentaje de tweets positivos es ", (positivo * 100)/ length(sentimentTweets$score), "% \n")
      cat("El porcentaje de tweets negativos es ", (negativo * 100)/ length(sentimentTweets$score), "% \n")
}

【问题讨论】:

  • 如果我有“情感分析”功能,我可以完成这项工作
  • 好的,我解释一下,该函数返回一个两行矩阵,第一行是给每条推文包含的分数,取决于正面或负面单词,第二行包含文本每条推文。
  • 请输入代码。或者在我下面发布的模板中尝试一下作为答案。
  • 该函数接收一个包含每条推文内容的向量,实际上,您不需要知道函数的内容,因为我的问题是如何将函数的结果写在屏幕上?
  • 我已经贴出了函数的代码

标签: r shiny


【解决方案1】:

score.sentiment = function(sentences, pos.words, neg.words) {

  # we got a vector of sentences. plyr will handle a list
  # or a vector as an "l" for us
  # we want a simple array ("a") of scores back, so we use 
  # "l" + "a" + "ply" = "laply":
  scores = laply(sentences, function(sentence, pos.words, neg.words) {

    # clean up sentences with R's regex-driven global substitute, gsub():
    sentence = gsub('[[:punct:]]', '', sentence)
    sentence = gsub('[[:cntrl:]]', '', sentence)
    sentence = gsub('\\d+', '', sentence)
    # and convert to lower case:
    sentence = tolower(sentence)

    # split into words. str_split is in the stringr package
    word.list = str_split(sentence, '\\s+')
    # sometimes a list() is one level of hierarchy too much
    words = unlist(word.list)

    # compare our words to the dictionaries of positive & negative terms
    pos.matches = match(words, pos.words)
    neg.matches = match(words, neg.words)

    # match() returns the position of the matched term or NA
    # we just want a TRUE/FALSE:
    pos.matches = !is.na(pos.matches)
    neg.matches = !is.na(neg.matches)

    # and conveniently enough, TRUE/FALSE will be treated as 1/0 by sum():
    score = sum(pos.matches) - sum(neg.matches)

    return(score)
  }, pos.words, neg.words)

  scores.df = data.frame(score=scores, text=sentences)
  return(scores.df)
}






sentimentalanalysis<-function(entity1text){

  # A compiled list of words expressing positive and negative sentiments ----
  #http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html
  # List of words and additional information on the original source from Jeffrey Breen's github site at:
  #https://github.com/jeffreybreen/twitter-sentiment-analysis-tutorial-201107/tree/master/data/opinion-lexicon-English

  positivewords=readLines("positive_words.txt")
  negativewords=readLines("negative_words.txt")

  #Applying score.sentiment algorithm to cleaned tweets and getting data frames of tweets, net sentiment score for a tweet 
  #(number of positive sentiments minus negative sentiments)

  entity1score = score.sentiment(CleanTweets(entity1text),positivewords,negativewords)

  return(entity1score)

}

【讨论】:

    【解决方案2】:

    这可以让你开始,但我没有足够的部分来完成它并让它工作。

    ui.R:

      shinyUI(
        sidebarPanel(textInput("term", "Put the term",""),
                 textInput("number","Number of tweets",""), 
                 submitButton("Search"),
                 mainPanel( h4("Results of the search"),
                            textOutput("result1"),
                            textOutput("result2"))
        )
      )
    

    服务器.R

    library(stringr)
    
    shinyServer(function(input, output) {
    
      score.sentiment = function(sentences, pos.words, neg.words) {
    
        # we got a vector of sentences. plyr will handle a list
        # or a vector as an "l" for us
        # we want a simple array ("a") of scores back, so we use 
        # "l" + "a" + "ply" = "laply":
        scores = laply(sentences, function(sentence, pos.words, neg.words) {
    
          # clean up sentences with R's regex-driven global substitute, gsub():
          sentence = gsub('[[:punct:]]', '', sentence)
          sentence = gsub('[[:cntrl:]]', '', sentence)
          sentence = gsub('\\d+', '', sentence)
          # and convert to lower case:
          sentence = tolower(sentence)
    
          # split into words. str_split is in the stringr package
          word.list = str_split(sentence, '\\s+')
          # sometimes a list() is one level of hierarchy too much
          words = unlist(word.list)
    
          # compare our words to the dictionaries of positive & negative terms
          pos.matches = match(words, pos.words)
          neg.matches = match(words, neg.words)
    
          # match() returns the position of the matched term or NA
          # we just want a TRUE/FALSE:
          pos.matches = !is.na(pos.matches)
          neg.matches = !is.na(neg.matches)
    
          # and conveniently enough, TRUE/FALSE will be treated as 1/0 by sum():
          score = sum(pos.matches) - sum(neg.matches)
    
          return(score)
        }, pos.words, neg.words)
    
        scores.df = data.frame(score=scores, text=sentences)
        return(scores.df)
      }
      sentimentalanalysis<-function(entity1text){
    
        # A compiled list of words expressing positive and negative sentiments ----
        #http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html
        # List of words and additional information on the original source from Jeffrey Breen's github site at:
        #https://github.com/jeffreybreen/twitter-sentiment-analysis-tutorial-201107/tree/master/data/opinion-lexicon-English
    
        positivewords=readLines("positive_words.txt")
        negativewords=readLines("negative_words.txt")
    
        #Applying score.sentiment algorithm to cleaned tweets and getting data frames of tweets, net sentiment score for a tweet 
        #(number of positive sentiments minus negative sentiments)
    
        #entity1score = score.sentiment(CleanTweets(entity1text),positivewords,negativewords)
        entity1score = score.sentiment(entity1text,positivewords,negativewords)
    
        return(entity1score)
    
      }  
      TweetFrame <- function(term,number)
      {
         s <- sprintf("%s%s",term,number)
         return(s)
      }
    
    myterm<-reactive({myterm<-TweetFrame(input$term, input$number)})
    
    #cleanterms <- reactive({CleanTweets(myterm()["text"])})
    cleanterms <- reactive({myterm()["text"]})
    
    
    
    sentimentsTweets<-reactive({sentimentsTweets<-sentimentalanalysis(cleanterms()["text"])})
    
    output$result1 <- renderPrint({paste(print(sentimentsTweets()["score"]))})
    
    CalculatePercentage<-function(sentimentTweets){
    
      neutral <- 0
      negativo <- 0
      positivo <- 0
    
      for(i in 1:length(sentimentTweets$score)){
    
        if(sentimentTweets$score[i] == 0){
          neutral <- neutral + 1 
        } else {
          if(sentimentTweets$score[i] > 0){
            positivo <- positivo + 1
          } else {
            negativo <- negativo + 1
          }
        }
    
      }
    
      cat("El porcentaje de tweets neutrales es ", (neutral * 100)/ length(sentimentTweets$score), "% \n")
      cat("El porcentaje de tweets positivos es ", (positivo * 100)/ length(sentimentTweets$score), "% \n")
      cat("El porcentaje de tweets negativos es ", (negativo * 100)/ length(sentimentTweets$score), "% \n")
    }
    
    output$result2 <- renderPrint({CalculatePercentage(as.vector(sentimentsTweets()))})
    })
    

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2020-07-31
      • 1970-01-01
      • 2022-01-13
      • 2021-01-09
      相关资源
      最近更新 更多