customer_id transaction_id month year
1 3 7 2014
1 4 7 2014
2 5 7 2014
2 6 8 2014
1 7 8 2014
3 8 9 2015
1 9 9 2015
4 10 9 2015
5 11 9 2015
2 12 9 2015我非常熟悉R基础知识。任何帮助都将不胜感激。
预期输出应如下所示:
month year number_unique_customers_added
7 2014 2
8 2014 0
9 2015 3在2014年第7月和第2年,只有customers_id 1和2存在,因此添加的客户数量为2。在2014年8月和2014年,不会添加新的客户ids。因此,在此期间应添加零个客户。最后在2015年和第9个月,customer_ids 3、4和5是新添加的。因此,在此期间添加的新客户数量为3。
发布于 2018-10-24 18:21:46
使用data.table
require(data.table)
dt[, .SD[1,], by = customer_id][, uniqueN(customer_id), by = .(year, month)]说明:我们首先删除每个客户的所有后续事务(当第一个客户是“新客户”时,我们对第一个感兴趣),然后按年和月的每个组合计算唯一客户。
发布于 2018-10-24 18:34:00
使用dplyr,我们可以首先创建一个列,指示客户是否重复,然后使用group_by、month和year来计算每个组中的新客户。
library(dplyr)
df %>%
mutate(unique_customers = !duplicated(customer_id)) %>%
group_by(month, year) %>%
summarise(unique_customers = sum(unique_customers))
# month year unique_customers
# <int> <int> <int>
#1 7 2014 2
#2 8 2014 0
#3 9 2015 3https://stackoverflow.com/questions/52904099
复制相似问题