Reputation: 99
So I have a table of customers with the respective date as below:
ID | Date |
---|---|
1 | 2019-04-17 |
4 | 2019-05-12 |
1 | 2019-04-25 |
2 | 2019-05-19 |
I just want to count how many Customer is there for each month-year like below:
Month-Year | Count of Customer |
---|---|
Apr-19 | 2 |
May-19 | 2 |
EDIT: Sorry but I think my Question should be clearer. The same customer can appear more than once in a month and would be counted as 2 customer for the same month. I would basically like to find the number of transaction per month based on customer id.
My assumed approach would be to first change the date into a month-year format? And then I count each customer and grouped it for each month? but I am not sure how to do this in R. Thank you!
Upvotes: 1
Views: 352
Reputation: 887098
We can use zoo::as.yearmon
library(dplyr)
df %>%
count(Date = zoo::as.yearmon(Date))
Date n
1 Apr 2019 2
2 May 2019 2
df <- structure(list(ID = c(1L, 4L, 1L, 2L), Date = c("2019-04-17",
"2019-05-12", "2019-04-25", "2019-05-19")),
class = "data.frame", row.names = c(NA, -4L))
Upvotes: 1
Reputation: 388982
You can use count
-
library(dplyr)
df %>% count(Month_Year = format(as.Date(Date), '%b-%y'))
# Month_Year n
#1 Apr-19 2
#2 May-19 2
Or table
in base R -
table(format(as.Date(df$Date), '%b-%y'))
#Apr-19 May-19
# 2 2
data
df <- structure(list(ID = c(1L, 4L, 1L, 2L), Date = c("2019-04-17",
"2019-05-12", "2019-04-25", "2019-05-19")),
class = "data.frame", row.names = c(NA, -4L))
Upvotes: 2