如何在R中将日期变量分组为月/年? [英] How do I group my date variable into month/year in R?

查看:324
本文介绍了如何在R中将日期变量分组为月/年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期"向量,其中包含mm/dd/yyyy格式的日期:

I have a "date" vector, that contains dates in mm/dd/yyyy format:

 head(Entered_Date,5)
[1] 1/5/1998 1/5/1998 1/5/1998 1/5/1998 1/5/1998

我正在尝试针对日期绘制频率变量,但是我想按月或年对日期进行分组.现在,每天都有一个频率,但是我想按月或年绘制频率.因此,我不想将1/5/1998的频率设为1,将1/7/1998的频率设为1,将1/8/1998的频率设为3,而是将1/1998的频率设为5.它是一个相对较大的数据集,其日期为1998年至今,我想找到一些自动化的方法来完成此任务.

I am trying to plot a frequency variable against the date, but I want to group the dates that it is by month or year. As it is now, there is a frequency per day, but I want to plot the frequency by month or year. So instead of having a frequency of 1 for 1/5/1998, 1 for 1/7/1998, and 3 for 1/8/1998, I would like to display it as 5 for 1/1998. It is a relatively large data set, with dates from 1998 to present, and I would like to find some automated way to accomplish this.

> dput(head(Entered_Date))
structure(c(260L, 260L, 260L, 260L, 260L, 260L), .Label = c("1/1/1998", 
"1/1/1999", "1/1/2001", "1/1/2002", "1/10/2000", "1/10/2001", 
"1/10/2002", "1/10/2003", "1/10/2005", "1/10/2006", "1/10/2007", 
"1/10/2008", "1/10/2011", "1/10/2012", "1/10/2013", "1/11/1999", 
"1/11/2000", "1/11/2001", "1/11/2002", "1/11/2005", "1/11/2006", 
"1/11/2008", "1/11/2010", "1/11/2011", "1/11/2012", "1/11/2013", 
"1/12/1998", "1/12/1999", "1/12/2001", "1/12/2004", "1/12/2005", ...

推荐答案

以下是使用dplyr的示例.您只需在format语句中为月份%m或年份%Y使用相应的日期格式字符串.

Here is an example using dplyr. You simply use the corresponding date format string for month %m or year %Y in the format statement.

set.seed(123)
df <- data.frame(date = seq.Date(from =as.Date("01/01/1998", "%d/%m/%Y"), 
                                 to=as.Date("01/01/2000", "%d/%m/%Y"), by="day"),
                 value = sample(seq(5), 731, replace = TRUE))

head(df)
        date value
1 1998-01-01     2
2 1998-01-02     4
3 1998-01-03     3
4 1998-01-04     5
5 1998-01-05     5
6 1998-01-06     1

library(dplyr)

df %>%
mutate(month = format(date, "%m"), year = format(date, "%Y")) %>%
group_by(month, year) %>%
summarise(total = sum(value))

Source: local data frame [25 x 3]
Groups: month [?]

   month  year total
   (chr) (chr) (int)
1     01  1998   105
2     01  1999    91
3     01  2000     3
4     02  1998    74
5     02  1999    77
6     03  1998    96
7     03  1999    86
8     04  1998    91
9     04  1999    95
10    05  1998    93
..   ...   ...   ...

这篇关于如何在R中将日期变量分组为月/年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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