Reputation: 4335
I have a dataset
dput(Data)
structure(list(Date = c(20170120L, 20170120L, 20170120L, 20170120L,
20170120L, 20170121L, 20170121L, 20170121L, 20170121L, 20170121L,
20170121L, 20170122L, 20170122L, 20170122L, 20170122L, 20170122L,
20170123L, 20170123L, 20170123L, 20170123L), Card = c(1207330L,
1873230L, 1556250L, 1395950L, 1395950L, 1393220L, 1058940L, 1556250L,
1395950L, 1395950L, 1058940L, 1207330L, 1058940L, 1700880L, 1395950L,
1055360L, 1395950L, 1556250L, 1207330L, 1395950L)), .Names = c("Date",
"Card"), class = "data.frame", row.names = c(NA, -20L))
and i am trying to get this stat
business_date New Card
20170120 4
20170121 2
20170122 2
20170123 0
On the First day - all unique new cards(1207330,1873230,1556250,1395950)
will be new cards. On the second day - all the unique cards for that second day will be compared to first day and those that are not repeated are New cards( 1393220,1058940)
. On the third day - need new cards that are not there in both First and second day(1700880,1055360)
and so on.
Upvotes: 0
Views: 44
Reputation: 70336
In base R this would be done by aggregate
ing the non-duplicated Cards per Date:
aggregate(!duplicated(df$Card), by = list(df$Date), FUN = sum)
# Group.1 x
#1 20170120 4
#2 20170121 2
#3 20170122 2
#4 20170123 0
Or in dplyr:
library(dplyr)
df %>%
mutate(count = !duplicated(Card)) %>%
group_by(Date) %>%
summarise(n = sum(count))
## A tibble: 4 × 2
# Date n
# <int> <int>
#1 20170120 4
#2 20170121 2
#3 20170122 2
#4 20170123 0
Upvotes: 2