如何按组有条件地计算唯一值

时间:2020-04-10 01:28:58

标签: r data.table

我每天都有用户记录。用户每天可以拥有多个记录。我想在为期3天的滚动窗口中统计唯一身份用户。我该如何实现?

set.seed(123)
dat<-data.table(day=rep(1:5,sample(6,5)))
dat$id<-sample(10,dat[,.N],replace=T)

> dat
    day id
 1:   1  1
 2:   1  6
 3:   2  9
 4:   2  6
 5:   2  5
 6:   2 10
 7:   3  5
 8:   3  7
 9:   3  6
10:   3  2
11:   3  9
12:   3  3
13:   4  1
14:   4  4
15:   4 10
16:   5  9
17:   5  7
18:   5  7
19:   5 10
20:   5  7

我想要的结果如下,即对于x天,我要计算x,x-1和x-2天的唯一ID的数量。

sqldf('select a.day,count(distinct b.id) as user_cnt 
  from dat as a left join dat as b on a.day<=b.day+2 and a.day>=b.day group by a.day')  

day user_cnt
1     2
2     5
3     8
4     9
5     9

1 个答案:

答案 0 :(得分:2)

通过多次阅读您的问题并检查所需的输出,您似乎想要一种自适应滚动的“独特”功能,该功能与 right (即 previous )对齐n天),以3天为一个窗口。

使用数据表应该是可能的,并且akrun提供了一种非自适应解决方案,其对齐方式为left。但是,您需要align ='right'(默认设置)。

library(data.table)

dt[, .(.(id)), day][
   , frollapply(seq_len(.N), n = 3, FUN = function(i) uniqueN(unlist(V1[i])))

[1] NA NA  8  9  9

请注意

dt[, .(.(id)), day]
   day             V1
1:   1            1,6
2:   2     9, 6, 5,10
3:   3    5,7,6,2,9,3
4:   4        1, 4,10
5:   5  9, 7, 7,10, 7

不幸的是,与其他功能(frollapplyfrollmean相比,data.table没有为frollsum函数提供部分(adaptive = TRUE)窗口选项。

我们可以尝试...

nk <- function(x, k) c(seq.int(k), rep(k, x - k))

dt[, .(.(id)), day][
    , frollapply(seq_len(.N), n = nk(.N, 3), FUN = function(i) uniqueN(unlist(V1[i])))

   V1 V2 V3 V4 V5
1:  2 NA NA NA NA
2:  4  5 NA NA NA
3:  6  7  8  8  8
4:  3  9  9  9  9
5:  3  5  9  9  9

但是我们得到了一个由5列组成的data.table,其答案潜伏在对角线上。

因此,我最终使用了mapply和用户定义的函数N_unique来计算滚动窗口返回的ID列表中的唯一值。我们仍然可以通过上面定义的nk函数使用部分窗口宽度。

N_unique <- function(i, width, x){
    uniqueN(unlist(x[(i - (width - 1)):i]))
}

dt2 <- dt[, .(.(id)), day][
  , user_cnt := mapply(FUN = N_unique, i = seq_len(.N), 
                       width = nk(.N, 3), MoreArgs = list(x = V1))][, V1:=NULL]
dt2
   day user_cnt
1:   1        2
2:   2        5
3:   3        8
4:   4        9
5:   5        9

数据

dput(dt)
structure(list(day = c(1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 
3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L), id = c(1, 6, 9, 6, 5, 
10, 5, 7, 6, 2, 9, 3, 1, 4, 10, 9, 7, 7, 10, 7)), row.names = c(NA, 
-20L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x0bae2498>)

注意:使用dt创建set.seed的命令产生了与OP提供的内容不同的结果。

相关问题