循环遍历R中的列表,对列表中的元素进行特定分析,将结果保存在元素数据框中?

我正在尝试在R中使用tidytext复制分析,但不使用循环。具体示例来自茱莉亚·席尔格(Julia Silge)和戴维·罗宾逊(David Robinson)的“文本挖掘与R”,一种简洁的方法。可以在这里找到其上下文:https://www.tidytextmining.com/sentiment.html#sentiment-analysis-with-inner-join

在本文中,他们举例说明了如何使用NRC词典进行情感分析,该词典具有八种不同的情感,包括喜悦,愤怒和期待。我没有像示例一样对特定书籍进行分析,因此我注释掉了这一行,它仍然有效:

nrc_list <- get_sentiments("nrc") %>% 
  filter(sentiment == "joy")

wordcount_joy <- wordcount %>%
# filter(book == "Emma") %>%
  inner_join(nrc_list) %>%
  count(word,sort = TRUE)

正如我之前所说,这可行。现在,我想对其进行修改以遍历所有八种情绪,并将结果保存在标有该情绪的数据框中。我如何修改它:

emotion <- c('anger','disgust','joy','surprise','anticip','fear','sadness','trust')

for (i in emotion) {

nrc_list <- get_sentiments("nrc") %>% 
  filter(sentiment == "i")

wcount[[i]] <- wordcount  %>%
  inner_join(nrc_list) %>%
  count(word,sort = TRUE)

}

执行此操作时,出现“错误:找不到对象'wcount'”消息。我已经用谷歌搜索了,似乎这个问题的答案是使用wcount [[i]],但是当我尝试修改它时,显然有些问题了。你有什么建议吗?

lip170 回答:循环遍历R中的列表,对列表中的元素进行特定分析,将结果保存在元素数据框中?

下面的代码可以解决问题。请注意,您在循环中引用的是单词计数,该示例使用的是整本书籍。代码遵循您所引用的tidytextmining链接中的步骤。

library(janeaustenr)
library(dplyr)
library(stringr)
library(tidytext)

tidy_books <- austen_books() %>%
  group_by(book) %>%
  mutate(linenumber = row_number(),chapter = cumsum(str_detect(text,regex("^chapter [\\divxlc]",ignore_case = TRUE)))) %>%
  ungroup() %>%
  unnest_tokens(word,text)

emotion <- c('anger','disgust','joy','surprise','anticip','fear','sadness','trust')
# initialize list with the length of the emotion vector
wcount <- vector("list",length(emotion))
# name the list entries
names(wcount) <- emotion

# run loop
for (i in emotion) {
  nrc_list <- get_sentiments("nrc") %>% 
    filter(sentiment == i)

  wcount[[i]] <- tidy_books  %>%
    inner_join(nrc_list) %>%
    count(word,sort = TRUE)
}
本文链接:https://www.f2er.com/3164484.html

大家都在问