简体   繁体   中英

Count and Aggregate Date in R

Below is the data that I have:

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

I would like to count the items by the month and year in Date column in R.

Below is the output I would like to achieve:

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

Thank you.

Just make sure you have the date in the proper format, then you can use cut and table , plus some formatting if you want to trim the days,

## 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

Assuming you're after monthly totals, I would use lubridate and dplyr :

library(lubridate)
library(dplyr)

data$Date <- dmy(data$Date)
data$date_formatted <- format(data$Date, "%m/%Y")

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

This gives the following output:

  date_formatted frequency
1        06/2015         2
2        09/2015         1
3        10/2015         1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM