【问题标题】:How to extract month from column如何从列中提取月份
【发布时间】: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 %&gt;% substr(start=6,stop=7) %&gt;% as.numeric 是一种非常有效的解决方法。

标签: r ggplot2 tidyr tidytext


【解决方案1】:

如果您想根据已有的日期列查看更小的时间单位,我建议您查看 lubridate 的 floor_date()round_date() 函数。您链接到的我们书中的特定章节涉及获取文档术语矩阵然后对其进行整理等。您是否已经为数据获得了整洁的文本格式?如果是这样,那么你可以这样做:

date_counts <- tidy_text %>%
    mutate(date = floor_date(Date, unit = "7 days")) %>% # use whatever time unit you want here
    count(date, word) %>%
    group_by(date) %>%
    mutate(date_total = sum(n))

date_counts %>%
    filter(word %in% c("PUT YOUR LIST OF WORDS HERE")) %>%
    ggplot(aes(date, n / date_total)) +
    geom_point() +
    geom_smooth() +
    facet_wrap(~ word, scales = "free_y")

【讨论】:

  • 谢谢,朱莉娅!我一直在读你的新书。我是 R 新手,但它非常有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多