【发布时间】:2017-11-15 12:15:20
【问题描述】:
我想从 Textmining with R 网络教科书中创建一个绘图,但使用我的数据。它基本上每年搜索最热门的术语并将它们绘制成图表(图 5.4:http://tidytextmining.com/dtm.html)。我的数据比他们开始使用的数据要干净一些,但我是 R 新手。我的数据有一个“日期”列,格式为 2016-01-01(它是一个日期类)。我只有 2016 年的数据,所以我想做同样的事情,但更细化(即按月或按天)
library(tidyr)
year_term_counts <- inaug_td %>%
extract(document, "year", "(\\d+)", convert = TRUE) %>%
complete(year, term, fill = list(count = 0)) %>%
group_by(year) %>%
mutate(year_total = sum(count))
year_term_counts %>%
filter(term %in% c("god", "america", "foreign", "union", "constitution",
"freedom")) %>%
ggplot(aes(year, count / year_total)) +
geom_point() +
geom_smooth() +
facet_wrap(~ term, scales = "free_y") +
scale_y_continuous(labels = scales::percent_format()) +
ylab("% frequency of word in inaugural address")
我的想法是我会从我的文本中选择我的特定单词,然后看看它们在几个月内的变化。
谢谢!
【问题讨论】:
-
欢迎来到 SO:您是否尝试过按功能分解
year_term_counts以检查中间步骤?您是否按预期建立结果?这将有助于我们查看一些数据。 -
您应该考虑使用
lubridate包中的month函数来制作包含月份的整个列。 -
我去看看月份功能,谢谢!
-
如果日期格式始终为 YYYY-MM-DD,我发现
as.character %>% substr(start=6,stop=7) %>% as.numeric是一种非常有效的解决方法。