我有一个在线购物平台的订单数据库。
我正在使用的表格如下所示,其中每一行对应一个客户/项目/日期。
OrderHistory <- data.frame(date=c("2015-02-01", "2015-03-01", "2015-04-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-05-01"),
customer=c("A","A","A","B","B","B","B"),
item=c("Candy", "Coffee", "Coffee", "Candy", "Candy", "Candy", "Coffee" ))
我想得到的是每位会员订购特定商品的次数的运行计数,因此我可以对同一客户重复订购哪些商品以及哪些商品订购一次而不再订购进行分析。
输出看起来像
out <- data.frame(date=c("2015-02-01", "2015-03-01", "2015-04-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-05-01"),
member=c("A","A","A","B","B","B","B"),
item=c("Candy", "Coffee", "Coffee", "Candy", "Candy", "Candy", "Coffee" ),
count=c(1,1,2,1,2,3,1))
我会喜欢一个dplyr解决方案,但我对任何建议持开放态度!平台上的确切项目不断变化,因此解决方案必须是动态的,以解决这个问题。
答案 0 :(得分:11)
我相信这会给你你想要的东西
library(dplyr)
OrderHistory %>%
group_by(customer, item) %>%
mutate(count = seq(n()))
Source: local data frame [7 x 4]
Groups: customer, item
date customer item count
1 2015-02-01 A Candy 1
2 2015-03-01 A Coffee 1
3 2015-04-01 A Coffee 2
4 2015-03-01 B Candy 1
5 2015-04-01 B Candy 2
6 2015-05-01 B Candy 3
7 2015-05-01 B Coffee 1
答案 1 :(得分:1)
你已经得到了你的&#34; dplyr&#34;回答,但基地R的一个简单方法是使用ave
:
ave(rep(1, nrow(OrderHistory)), OrderHistory[-1], FUN = seq_along)
# [1] 1 1 2 1 2 3 1
您也可以使用我的&#34; splitstackshape&#34;中的getanID
包:
library(splitstackshape)
getanID(OrderHistory, c("customer", "item"))
# date customer item .id
# 1: 2015-02-01 A Candy 1
# 2: 2015-03-01 A Coffee 1
# 3: 2015-04-01 A Coffee 2
# 4: 2015-03-01 B Candy 1
# 5: 2015-04-01 B Candy 2
# 6: 2015-05-01 B Candy 3
# 7: 2015-05-01 B Coffee 1