如何解决按日期的情绪分析
我正在对每天持续增长的大量数据进行一些非常基本的情绪分析。我需要将这些数据输入到一个闪亮的应用程序中,我可以在其中调整日期范围。我想做的不是一遍又一遍地运行分析,而是创建一个新的 CSV,其中包含按日期的每个情绪分数的总和。不过,我在迭代日期时遇到了麻烦。这是一些示例数据和我尝试过的 lapply()
语句不起作用。
library(tidyverse)
library(syuzhet)
library(data.table)
df <- data.frame(date = c("2021-01-18","2021-01-18","2021-01-17","2021-01-16","2021-01-15","2021-01-15"),text = c("Some text here","More text","Some other words","Just making this up","as I go along","hope the example helps","thank you in advance","I appreciate the help","the end"))
> df
date text
1 2021-01-18 Some text here
2 2021-01-18 More text
3 2021-01-18 Some other words
4 2021-01-17 Just making this up
5 2021-01-17 as I go along
6 2021-01-16 hope the example helps
7 2021-01-15 thank you in advance
8 2021-01-15 I appreciate the help
9 2021-01-15 the end
dates_scores_df <- lapply(df,function(i){
data <- df %>%
# Filter to the unique date
filter(date == unique(df$date[i]))
# Sentiment Analysis for each date
sentiment_data <- get_nrc_sentiment(df$text)
# Convert to df
score_df <- data.frame(sentiment_data[,])
# Transpose the data frame and adjust column names
daily_sentiment_data <- transpose(score_df)
colnames(daily_sentiment_data) <- rownames(score_df)
# Add a date column
daily_sentiment_data$date <- df$date[i]
})
sentiment_scores_by_date <- do.call("rbind.data.frame",dates_scores_df)
我想得到的是这样的东西(这里的数据是编造的,与上面的例子不符)
date anger anticipation disgust fear joy sadness surprise trust negative positive
2021-01-18 1 2 0 1 2 0 2 1 1 2
2021-01-17 1 2 0 2 3 3 1 2 0 1
解决方法
你可以试试:
library(dplyr)
library(purrr)
library(syuzhet)
df %>%
split(.$date) %>%
imap_dfr(~get_nrc_sentiment(.x$text) %>%
summarise(across(.fns = sum)) %>%
mutate(date = .y,.before = 1)) -> result
result
,
函数 lapply
迭代列表的元素。从技术上讲,数据框是一个列表,每一列都是该列表的一个元素。因此,在您的示例中,您正在迭代列而不是行,甚至日期(这似乎是您的目标)。我会将 lapply
与以下之一结合使用,而不是 dplyr::group_by
:dplyr::do
、dplyr::summarize
或 tidyr::nest
。查看每个函数的文档,以确定哪个函数最适合您的需求。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。