在R环境中;假设我有一个类似于下面的数据集:
ID活动1 a1 b2 a3 c2 a1 c4 a4 b3 b4 c正如您所看到的,每个ID都有一系列的…
这是一个data.table的解决方案
library(data.table) dt <- data.table(ID=c(1,1,2,3,2,1,4,4,3,4),Activity=c("a","b","a","c","a","c","a","b","b","c"))
每个序列的ID:
dt[,.(seq=paste(Activity,collapse = ",")),ID][,.(ids=paste(ID,collapse = ",")),seq]
我们可以得到一个快速的答案:
consecutive_id <- dt[,.(first=(Activity),second=(shift(Activity,type = "lead"))),ID][!is.na(second)] consecutive <- consecutive_id[,.N,.(first,second)]
但如果您需要在矩阵形式中需要一些额外的步骤:
classes <- dt[,unique(Activity)];n <- length(classes) M_consecutive <- data.table(matrix(0,nrow = n,ncol=n)) setnames(M_consecutive,classes) M_consecutive$classes <- classes; setkey(M_consecutive,classes) for(i in 1:nrow(consecutive)) M_consecutive[consecutive[i]$first,(consecutive[i]$second):=consecutive[i]$N] M_consecutive