我想探索data.table
分组的优雅(单线)解决方案
我有data.table
如下:
library(data.table)
library(lubridate)
dt.master <- data.table(user = c(1000, 1002, 2008, 3005, 1000, 1002, 1002),
target = c(50000, 50004, 50501, 50001, 50000, 50000, 50004),
channel = c("A", "B", "C", "A", "B", "A", "C"),
date = c(dmy("10/02/2018"), dmy("11/04/2018"), dmy("14/03/2018"), dmy("02/03/2018"), dmy("05/01/2018"), dmy("08/05/2018"), dmy("05/03/2018")))
那是:
user target channel date
1: 1000 50000 A 2018-02-10
2: 1002 50004 B 2018-04-11
3: 2008 50501 C 2018-03-14
4: 3005 50001 A 2018-03-02
5: 1000 50000 B 2018-01-05
6: 1002 50000 A 2018-05-08
7: 1002 50004 C 2018-03-05
我想知道,对于每组(user, target)
,第一个发生的通道,并将其添加到dt.master。这是:
user target channel date first_channel
1: 1000 50000 A 2018-02-10 B
2: 1000 50000 B 2018-01-05 B
3: 1002 50000 A 2018-05-08 A
4: 1002 50004 B 2018-04-11 C
5: 1002 50004 C 2018-03-05 C
6: 2008 50501 C 2018-03-14 C
7: 3005 50001 A 2018-03-02 A
目前,我分两步进行:
首先,我提取第一次出现的行
dt.result <- dt.master[dt.master[, .(first_interest = .I[which.min(date)]), by = c("user", "target")]$first_interest,]
之后,我将其与dt.master
setnames(dt.result, "channel", "first_channel")
dt.master <- merge(dt.master, dt.result[, .(user, target, first_channel)],
by.x = c("user", "target"), by.y = c("user", "target"),
all.x = T, all.y = F)
有没有办法在没有合并的情况下做到这一点?我认为必须有修改第一行的解决方案,但我找不到它。
非常感谢!
答案 0 :(得分:1)
您可以按照以下方式按组参考更新:
dt.master[, first_channel := channel[which.min(date)], keyby=.(user, target)]
答案 1 :(得分:0)
[ 1 12]