使用循环将值加载到列表中

时间:2015-02-09 01:56:40

标签: r

我正在尝试使用R进行情绪分析。我的代码如下。 我试图提取积极和消极的话来创建词云。因此,我试图获取输入文件中的正面和负面单词列表。

library(tm)
library(wordcloud)
library(plyr)
library(sentiment)
require(stringr)
pos.words=scan('positive-words.txt',what='character',comment.char=';')
neg.words=scan('negative-words.txt',what='character',comment.char=';')

data <- readLines("input.txt")

'''
clean the input

'''


# split into words. str_split is in the stringr package

word.list = str_split(cleaned, '\\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)

这是我试图实现提取否定词的for循环。但我只从列表中得到一个字。

for (w in neg.matches)
  if(!is.na(w))
    negit <- neg.words[w]

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

count = 0
for (w in neg.matches)
{  
  if(!is.na(w))
  {    
    count = count + 1
  }  

}  

negit = array(dim=c(count-1))
i = 0
for (w in neg.matches)
{  
  if(!is.na(w))
  {
    negit[i] <- neg.words[w]
    i = i + 1
  }  

}   

count = 0
for (w in pos.matches)
{  
  if(!is.na(w))
  {    
    count = count + 1
  }  

}  

posit = array(dim=c(count-1))
i = 0
for (w in pos.matches)
{  
  if(!is.na(w))
  {
    posit[i] <- pos.words[w]
    i = i + 1
  }  

}