2015-10-15 48 views
0

下面總結日期是數據,我有:計數和分別在R

Item Date 
Apple 09/06/2015 
Orange 19/06/2015 
Pear 01/09/2015 
Kiwi 20/10/2015 

我想計數R.

低於月份和年份日期列中的項目被輸出我想實現:

Date  Frequency 
05/2015 0 
06/2015 2 
07/2015 0 
08/2015 0 
09/2015 1 
10/2015 1 

謝謝。

+1

嘗試'table'函數。 – ako

回答

3

只要確保你有適當的格式日期,那麼你可以使用cuttable,加上一些格式,如果你想修剪天,

## Convert to date 
dat$Date <- as.Date(dat$Date, format="%d/%m/%Y") 

## Tabulate 
tab <- table(cut(dat$Date, 'month')) 

## Format 
data.frame(Date=format(as.Date(names(tab)), '%m/%Y'), 
      Frequency=as.vector(tab)) 
#  Date Frequency 
# 1 06/2015   2 
# 2 07/2015   0 
# 3 08/2015   0 
# 4 09/2015   1 
# 5 10/2015   1 
1

假設你每月彙總後的時候,我會用lubridatedplyr

library(lubridate) 
library(dplyr) 

data$Date <- dmy(data$Date) 
data$date_formatted <- paste(month(data$Date), "/", year(data$Date), sep = "") 

data %>% group_by(date_formatted) %>% summarise(frequency = n()) 

這給出了以下的輸出:

date_formatted frequency 
1  10/2015   1 
2   6/2015   2 
3   9/2015   1 
+1

這不是OP的預期輸出。 – 2015-10-15 04:44:41