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

Loop over list in R, conduct analysis specific to element in list, save results in element dataframe?

我正在尝试使用 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)

}

我在执行此操作时收到 "Error: object 'wcount' not found" 消息。我已经用谷歌搜索了这个问题,这个问题的答案似乎是使用 wcount[[i]] 但是当我尝试调整它时显然有些问题。你有什么建议吗?

下面的代码可以解决问题。请注意,您在循环中引用了 wordcount,并且该示例使用了 tidybooks。代码遵循 link 中的步骤以整理您所指的文本挖掘。

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)
}