I am trying to transform my data manipulation code from dplyr
to data.table
for speed reasons. I am almost there but missing the final step.
I have some sample data to replicate my problem.
c_dt = data.table(u_id=rep(c("u1", "u2"),each=5),
p_id=c("p1", "p1", "p1", "p2","p2", "p1", "p2", "p2", "p2", "p2" ),
c_dt=c("2015-12-01", "2015-12-02", "2015-12-03", "2015-12-02",
"2015-12-05", "2015-12-02", "2015-12-03", "2015-12-04",
"2015-12-05", "2015-12-06"))
I wish to identify the rows where u_id
and p_id
is duplicated; and keep only the row with the minimum c_dt
(essentially keep the first instance). I use the following dplyr
code for this:
c_df <- as.data.frame(c_dt)
cdedup_df <- c_df %>% group_by(p_id, u_id) %>% filter(c_dt == min(c_dt))
Which give the below output
> cdedup_df
Source: local data frame [4 x 3]
Groups: p_id, u_id
u_id p_id c_dt
1 u1 p1 2015-12-01
2 u1 p2 2015-12-02
3 u2 p1 2015-12-02
4 u2 p2 2015-12-03
I have the following data.table
code that correctly identifies the required rows but I am unable to figure out how to just filter and the row as it is.
cdedup_dt <- c_dt[,c_dt == min(c_dt),by = list(u_id, p_id)]
cdedup_dt
u_id p_id V1
1: u1 p1 TRUE
2: u1 p1 FALSE
3: u1 p1 FALSE
4: u1 p2 TRUE
5: u1 p2 FALSE
6: u2 p1 TRUE
7: u2 p2 TRUE
8: u2 p2 FALSE
9: u2 p2 FALSE
10: u2 p2 FALSE