我有会话ID,客户ID,转换列,并且都带有特定日期。我要在最后一次购买客户后删除这些行。我的数据如下:
SessionId ClientId Conversion Date
1 1 0 05-01
2 1 0 06-01
3 1 0 07-01
4 1 1 08-01
5 1 0 09-01
6 2 0 05-01
7 2 1 06-01
8 2 0 07-01
9 2 1 08-01
10 2 0 09-01
我想要的输出:
SessionId ClientId Conversion Date
1 1 0 05-01
2 1 0 06-01
3 1 1 07-01
6 2 0 05-01
7 2 1 06-01
8 2 0 07-01
9 2 1 08-01
我看起来很简单,但是有一些条件。根据客户ID,需要删除上次购买用户后的会话。我有很多发现,因此无法在特定日期之后删除。它需要检查有人购买时的每个客户ID。
我不知道我需要使用哪种功能。也许是某种循环?
希望有人可以帮助我。
我们可以尝试
library(dplyr)
df1 %>%
group_by(ClientId) %>%
slice(seq_len(tail(which(Conversion == 1), 1)))
df1 <- structure(list(SessionId = 1:10, ClientId = c(1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L), Conversion = c(0L, 0L, 0L, 1L, 0L, 0L,
1L, 0L, 1L, 0L), Date = c("05-01", "06-01", "07-01", "08-01",
"09-01", "05-01", "06-01", "07-01", "08-01", "09-01")),
class = "data.frame", row.names = c(NA,
-10L))
如果您的数据已经根据Date
进行了排序,则对于每个ClientId
,我们都可以选择上一次转换之前的所有行。
这可以在基数R中完成:
subset(df, ave(Conversion == 1, ClientId, FUN = function(x) seq_along(x) <= max(which(x))))
使用dplyr
:
library(dplyr)
df %>% group_by(ClientId) %>% filter(row_number() <= max(which(Conversion == 1)))
或data.table
:
library(data.table)
setDT(df)[, .SD[seq_len(.N) <= max(which(Conversion == 1))], ClientId]