0

R twitteR パッケージの初心者向けチュートリアルに従っていますが、障害に遭遇しました。(チュートリアルURL: https://sites.google.com/site/miningtwitter/questions/sentiment/analysis )

セクション 4 で説明した searchTwitter 関数を使用してツイートのリストをインポートするのではなく、MySQL データベースからツイートのデータ フレームをインポートしています。MySQL からツイートを正常にインポートできますが、実行しようとすると:

wine_txt = sapply(wine_tweets, 関数(x) x$getText())

エラーが発生します:

x$getText のエラー: $ 演算子は原子ベクトルに対して無効です

データは既に data.frame 形式であり、その後、確認のためにもう一度 data.frame に強制しましたが、それでも同じエラーが発生します。以下に完全なコードを貼り付けました。

library(twitteR)
library(plyr)
library(stringr)
library(RMySQL)

tweets.con<-dbConnect(MySQL(),user="XXXXXXXX",password="XXXXXXXX",dbname="XXXXXXX",host="XXXXXXX")
wine_tweets<-dbGetQuery(tweets.con,"select `tweet_text` from `tweets` where `created_at` BETWEEN timestamp(DATE_SUB(NOW(), INTERVAL 11 MINUTE)) AND timestamp(NOW())")

# function score.sentiment
score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
# Parameters
# sentences: vector of text to score
# pos.words: vector of words of postive sentiment
# neg.words: vector of words of negative sentiment
# .progress: passed to laply() to control of progress bar

# create simple array of scores with laply
scores = laply(sentences,
function(sentence, pos.words, neg.words)
{
  # remove punctuation
  sentence = gsub("[[:punct:]]", "", sentence)
  # remove control characters
  sentence = gsub("[[:cntrl:]]", "", sentence)
  # remove digits?
  sentence = gsub('\\d+', '', sentence)

  # define error handling function when trying tolower
  tryTolower = function(x)
  {
     # create missing value
     y = NA
     # tryCatch error
     try_error = tryCatch(tolower(x), error=function(e) e)
     # if not an error
     if (!inherits(try_error, "error"))
     y = tolower(x)
     # result
     return(y)
  }
  # use tryTolower with sapply 
  sentence = sapply(sentence, tryTolower)

  # split sentence into words with str_split (stringr package)
  word.list = str_split(sentence, "\\s+")
  words = unlist(word.list)

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

  # get 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)

  # final score
  score = sum(pos.matches) - sum(neg.matches)
  return(score)
  }, pos.words, neg.words, .progress=.progress )

# data frame with scores for each sentence
scores.df = data.frame(text=sentences, score=scores)
return(scores.df)
}

# import positive and negative words
pos = readLines("/home/jgraab/R/scripts/positive_words.txt")
neg = readLines("/home/jgraab/R/scripts/negative_words.txt")
wine_txt = sapply(wine_tweets, function(x) x$getText())
4

1 に答える 1