问题描述
readtext object consisting of 6 documents and 8 docvars.
# Description: df[,10] [6 × 10]
doc_id text year month day hour minute second title source
* <chr> <chr> <int> <int> <int> <int> <int> <int> <chr> <chr>
1 2014_01_01_10_51_00… "\"新华网伦敦1… 2014 1 1 10 51 0 docid报告称若不减… RMWenv
2 2014_01_01_11_06_00… "\"新华网北京1… 2014 1 1 11 6 0 docid盘点2013… RMWenv
3 2014_01_02_08_08_00… "\"原标题:报告… 2014 1 2 8 8 0 docid报告称若不减… RMWenv
4 2014_01_03_08_42_00… "\"地球可能毁灭… 2014 1 3 8 42 0 docid地球可能毁灭… RMWenv
5 2014_01_03_08_44_00… "\"北美鼠兔看起… 2014 1 3 8 44 0 docid北美鼠兔为应… RMWenv
6 2014_01_06_10_30_00… "\"欣克力C点核… 2014 1 6 10 30 0 docid英国欲建50… RMWenv
我想衡量在这些文章中出现特定术语(例如“发展”)的变化相对频率(以占文章总数的比例/或特定日期/月份发表的所有文章中总条款的百分比)。我知道我可以使用以下方法计算一个月内所有文章中该词出现的次数:
dfm(corp,select = "term",groups = "month")
我可以使用以下方法获得单词相对于文档中单词总数的相对频率:
dfm_weight(dfm,scheme = "prop")
但是我如何将它们组合在一起以获得特定术语相对于特定日期或特定月份中单词总数的频率?
我想做的是测量一个术语的使用次数随时间的变化,但要考虑到所用单词的总数也在变化的事实。感谢您的帮助!
解决方法
@DaveArmstrong在这里给出了一个很好的答案,我对此表示赞同,但是可以使用一些更简单的 quanteda 语法来提高效率。
此处的键是保留zoo::yearmon()
创建的日期格式,因为dfm分组会将其强制为字符。因此,我们将其打包到一个docvar中,由分组保存,然后在ggplot()
调用中进行检索。
load(file("https://www.dropbox.com/s/kl2cnd63s32wsxs/music.rda?raw=1"))
library("quanteda")
## Package version: 2.1.1
## create corpus and dfm
corp <- corpus(m,text_field = "body_text")
corp$date <- m$first_publication_date %>%
zoo::as.yearmon()
D <- dfm(corp,remove = stopwords("english")) %>%
dfm_group(groups = "date") %>%
dfm_weight(scheme = "prop")
library("ggplot2")
convert(D[,"wonderfully"],to = "data.frame") %>%
ggplot(aes(x = D$date,y = wonderfully,group = 1)) +
geom_line() +
labs(x = "Date",y = "Wonderfully/Total # Words")
,
我怀疑有人会在quanteda
中提出更好的解决方案,但是如果他们没有,您总是可以从dfm
中提取单词并将其与日期,然后绘制图表。在下面的代码中,我使用了从《卫报》网站上抓取的一些音乐评论。我已经注释掉了从Dropbox的.rda
文件中读取数据的函数。欢迎您随意使用它-它很干净,但我不想无意间让某人从他们不知道的网络上下载文件。
# f <- file("https://www.dropbox.com/s/kl2cnd63s32wsxs/music.rda?raw=1")
# load(f)
## create corpus and dfm
corp <- corpus(as.character(m$body_text))
docvars(corp,"date") <- m$first_publication_date
D <- dfm(corp,remove=stopwords("english"))
## take word frequencies "wonderfully" in the dfm
## along with the date
tmp <- tibble(
word = as.matrix(D)[,date = docvars(corp)$date,## calculate the total number of words in each document
total = rowSums(D)
)
tmp <- tmp %>%
## turn date into year-month
mutate(yearmon =zoo::as.yearmon(date)) %>%
## group by year-month
group_by(yearmon) %>%
## calculate the sum of the instances of "wonderfully"
## divided by the sum of the total words across all
## documents in the month
summarise(prop = sum(word)/sum(total))
## make a plot.
ggplot(tmp,aes(x=yearmon,y=prop)) +
geom_line() +
labs(x= "Date",y="Wonderfully/Total # Words")