我有一个数据集
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))
我试图得到这个统计数据
business_date New Card
20170120 4
20170121 2
20170122 2
20170123 0
在第一天 - 所有独特的新卡(1207330,1873230,1556250,1395950)
都将是新卡。在第二天 - 第二天的所有唯一卡片将与第一天进行比较,而不重复的那些卡片将是新卡片( 1393220,1058940)
。在第三天 - 需要第一天和第二天(1700880,1055360)
不存在的新卡片等等。
答案 0 :(得分:2)
在基数R中,这将通过aggregate
每个日期的非重复卡片来完成:
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
或者在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