700.000 行以上のデータフレーム (myDF) があり、各行には id と text の 2 つの列があります。テキストには 140 文字のテキスト (ツイート) が含まれており、Web から取得したセンチメント分析を実行したいと考えています。ただし、何を試しても、4 GB RAM の MacBook でメモリの問題が発生します。
行をループできるのではないかと考えていました。たとえば、最初の 10 を実行し、次に 2 番目の 10 を実行するなどです。(100 個のバッチでも問題が発生します) これで問題は解決しますか? そのような方法でループする最良の方法は何ですか?
ここにコードを投稿しています:
library(plyr)
library(stringr)
# 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)
{
# 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("positive_words.txt")
neg = readLines("negative_words.txt")
# apply function score.sentiment
myDF$scores = score.sentiment(myDF$text, pos, neg, .progress='text')