首页 > 解决方案 > 在R中循环列表,对列表中的元素进行特定的分析,将结果保存在元素数据框中?

问题描述

我正在尝试使用 R 中的 tidytext 复制分析,但使用循环除外。具体示例来自 Julia Silge 和 David Robinson 的 Text Mining with R, a Tidy Approach。它的上下文可以在这里找到: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]] 但很明显,当我尝试调整它时,有些东西出了问题。你有什么建议吗?

标签: rloopsfor-looptidytext

解决方案


下面的代码可以解决问题。请注意,您在循环中引用了 wordcount,并且该示例使用了 tidybooks。代码遵循您所指的 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)
}

推荐阅读