Reputation: 341
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.
Upvotes: 3
Views: 18049
Reputation: 597
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
Upvotes: 3
Reputation: 32426
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
Upvotes: 9