r - 在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]] 但很明显,当我尝试调整它时,有些东西出了问题。你有什么建议吗?
解决方案
下面的代码可以解决问题。请注意,您在循环中引用了 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)
}
推荐阅读
- python - 集线器连接未在 Python 中使用 SignalR 调用服务器方法
- c - if (strcmp(file_name, "stdout") == 0)?
- javascript - 尝试验证 sessionStorage 令牌并替换路径 - 在 reactjs 中不起作用
- java - 在 JavaFX 中,如何将字段声明为私有?
- django - 在 Django/Djongo 的另一个抽象模型中是否可以有一个抽象模型?
- sql - 从字符串中删除日期,转换为日期并检查是否等于今天的日期
- deep-learning - 有没有一种方便的方法可以只将 Pytorch 中的模型架构信息保存到 protobuf 规则文件中?
- terraform - 在通过 Terraform 部署初始 SQS 队列后添加 DLQ?
- android - 每X秒杀一次后如何打开android应用程序?
- ruby-on-rails - 如何遍历json导致ruby on rails?