table1 <- data.frame(user_id=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2),
product_id = c(14, 24, 38, 40, 66, 2, 19, 30, 71, 98, 7, 16),
first_order = c(1, 2, 1, 4, 5, 3, 2, 4, 2, 4, 2, 3),
last_order = c(4, 7, 5, 8, 8, 3, 4, 7, 5, 9, 4, 5))
table2 <- data.frame(user_id=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2),
order_number=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6),
days_cumsum = c(0, 7, 15, 26, 34, 43, 53, 59, 66, 74, 82, 91, 5, 11, 17, 24, 29, 35))
我想使用 table2 向 table1 添加新功能。
新功能是每个用户对每种产品的订购间隔。
例如,让我们看一下表1。第一行有(user_id==1)、(product_id==14)、(第一个订单==1)和(最后一个订单==4)。这意味着产品 14 是按订单 1、2、3、4 订购的。我们可以在表 2 中找到该订单号。
新功能是关于第一个订单和最后一个订单之间的订单间隔。我们可以在表 2 中使用“days_cumsum”得出它,它是先前订单后天数的累积总和。第一行的新特征值为26(=26-0)。
我认为这可以通过 join 完成,但是我无法使用加入因为实际上每张桌子都很大。
所以我在 for 循环中使用下面的这个函数:
f <- function(i){
a <- table2 %>%
filter(user_id==table1[i, 1]) %>%
filter(order_number==table1[i, 3] | order_number==table1[i, 4])
ifelse(nrow(a)==2, a[2, 3] - a[1, 3], 999999) # first_order==last_order
}
它逐行计算每个新的特征值,但速度很慢并且需要大量计算。我经常遇到这个问题(使用两个表创建新功能),但每次我都会遇到困难。
有更好的代码吗?我正在等待你的帮助。