在R中将YYYY-MM-DD转换为YYYY-YY Qx [英] Convert YYYY-MM-DD to YYYY-YY Qx in R

查看:53
本文介绍了在R中将YYYY-MM-DD转换为YYYY-YY Qx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按季度绘制数据,然后在ggplot中显示. dataset 中的日期格式为YYYY-MM-DD,我希望ggplot x轴显示财务年度,如YYYY-YY Qx.财政年度从7月1日开始.

I'm trying to plot data by quarter then display in ggplot. Dates in dataset are of the format YYYY-MM-DD, and I want the ggplot x-axis to display the financial year like YYYY-YY Qx. The financial year starts July 1.

数据为长格式.这是我必须去的地方:

Data is in long format. This is where I've got to:

      Data set named: TOX

TREE_ID    PM_Date                        variable value
1: 2013000584 2013-04-02               elm           0
2: 2013000498 2013-06-11               elm           1
3: 2013000123 2013-09-03               maple         0
4: 2013000642 2014-02-15               maple         0
5: 2013000778 2016-07-08               maple         1

PM_Dateq <- as.yearqtr(TOX$PM_Date, format)

Tox_longer_yr <- TOX [,list(value=sum(value)), by=list(PM_Dateq, variable)]

ggplot(Tox_longer_yr, aes(x = PM_Dateq, y = value, colour = variable)) 
+ geom_line()      

X轴当前显示为:

2015, 2016, 2017...etc 

(尽管它已正确地在ggplot中分组为四分之一.)

(Though it is grouped into quarters in ggplot correctly.)

我希望x轴看起来像这样:

I want the x-axis to look like:

2015-16 Q3, 2015-16 Q4, 2016-17 Q1, 2016-17 Q2...etc

因此,将2016年2月13日发生的事件归为"2015-16第3季度".

So an event happening on 2016-02-13 would be grouped into "2015-16 Q3".

推荐答案

这样的事情怎么样.

library(lubridate)
df %>%
    mutate(
        PM_Date = as.Date(PM_Date),
        Qtr = sprintf("%s-%s Q%i",
            year(PM_Date),
            year(PM_Date %m+% years(1)),
            cut(
                month(tmp$PM_Date),
                breaks = c(0, 3, 6, 9, 12),
                labels = c("Q3", "Q4", "Q1", "Q2")))) %>%
    group_by(Qtr, variable) %>%
    summarise(value = sum(value)) %>%
    ggplot(aes(x = Qtr, y = value, colour = variable, group = variable)) +
    geom_line()

说明:我们通过从 PM_Date 中提取年份,并对月份进行分箱,以 YYYY-YYYY QX 的形式构造一个新的 Qtr 变量.从7月1日开始使用 cut 放入3个月的垃圾箱中.我们使用 lubridate 轻松提取年份和日期算术"(对于第二个 YYYY ,我们在当年添加一年).

Explanation: We construct a new Qtr variable in the form YYYY-YYYY QX by extracting the year from PM_Date, and binning the months into 3 month bins starting from 1 July using cut. We use lubridate for easy extraction of the year and "date arithmetic" (for the second YYYY we add one year to the current year).

df <- read.table(text =
    "TREE_ID    PM_Date                        variable value
2013000584 2013-04-02               elm           0
2013000498 2013-06-11               elm           1
2013000123 2013-09-03               maple         0
2013000642 2014-02-15               maple         0
2013000778 2016-07-08               maple         1", header = T)

这篇关于在R中将YYYY-MM-DD转换为YYYY-YY Qx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆