2015-10-19 147 views
9

我有一個「約會」載體,包含以mm/dd/yyyy格式的日期:如何在R中將日期變量分組爲月/年?

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

我想暗算日期的頻率可變,但我想組的日期,它是按月或按年。就像現在一樣,每天都有一個頻率,但我想按月或年來計算頻率。因此,1998年1月5日的頻率爲1,1998年7月1日爲1,1998年8月1日爲3,我想在1998年1月5日顯示爲5。這是一個相對較大的數據集,從1998年到現在的日期,我想找到一些自動化的方法來實現這一點。

> 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", ... 
+2

爲了確保結果具有可重複性,請將輸出的o f'dput(head(Entered_Date))' –

+0

查看'zoo'包中的'as.yearmon'。 – Jaap

回答

13

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

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 
.. ... ... ... 
+0

就像一個魅力工作謝謝 –

+0

有一件事,我怎麼得到的月顯示爲月份的名稱,而不是數字? –

+0

@Learning_R您需要提供完整可重複的數據集。你的'dput'被截斷了,所以我不能讓你的數據重現這個標籤問題,我的例子提供了這個名字。 – cdeterman

1

也許你只是在你的數據添加一列這樣的:

Year <- format(as.Date(Entered_Date, "%d/%m/%Y"), "%Y")

+0

如果我想要月份和年份,例如1/2000,2/2000,... –

+0

,我將如何做,將括號前的最後一位更改爲「%m /%Y」...''strptime'將爲您提供所有這些日期格式選項的關鍵。 –

1

不需要dplyr。看看?as.POSIXlt

df$date<-as.POSIXlt(df$date) 
mon<-df$date$mon 
yr<-df$date$year 
monyr<-as.factor(paste(mon,yr,sep="/")) 
df$date<-monyr 

不需要使用ggplot2但其漂亮了這種事情。

c <- ggplot(df, aes(factor(date))) 
c + geom_bar() 

如果你想看到實際數字

aggregate(. ~ date,data = df,FUN=length) 
df2<-aggregate(. ~ date,data = df,FUN=length) 
df2 
    date value 
1 0/98 31 
2 0/99 31 
3 1/98 28 
4 1/99 28 
5 10/98 30 
6 10/99 30 
7 11/97  1 
8 11/98 31 
9 11/99 31 
10 2/98 31 
11 2/99 31 
12 3/98 30 
13 3/99 30 
14 4/98 31 
15 4/99 31 
16 5/98 30 
17 5/99 30 
18 6/98 31 
19 6/99 31 
20 7/98 31 
21 7/99 31 
22 8/98 30 
23 8/99 30 
24 9/98 31 
25 9/99 31 
0

有使用cut()函數一個超級簡單的方法:

list = as.Date(c("1998-5-2", "1993-4-16", "1998-5-10")) 
    cut(list, breaks = "month") 

,你會得到這樣的:

[1] 1998-05-01 1993-04-01 1998-05-01 
    62 Levels: 1993-04-01 1993-05-01 1993-06-01 1993-07-01 1993-08-01 ... 1998-05-01 
相關問題