我有一个带有列id
(主键)和featureCode
(分类变量)的"长格式"数据框.每个记录具有1到9个分类变量的值.例如:
id featureCode
5 PPLC
5 PCLI
6 PPLC
6 PCLI
7 PPL
7 PPLC
7 PCLI
8 PPLC
9 PPLC
10 PPLC
Run Code Online (Sandbox Code Playgroud)
我想计算每个特征代码与其他特征代码一起使用的次数(标题的"成对计数").在此阶段,使用每个要素代码的顺序并不重要.我设想结果将是另一个数据框,其中行和列是特征代码,单元格是计数.例如:
PPLC PCLI PPL
PPLC 0 3 1
PCLI 3 0 1
PPL 1 1 0
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不知道如何执行这个计算,我在搜索建议时画了一个空白(大多数情况下,我怀疑,因为我不知道正确的术语).
这是一种data.table
类似于@mrdwab 的方法
如果featureCode
是a ,它将最有效character
library(data.table)
DT <- data.table(dat)
# convert to character
DT[, featureCode := as.character(featureCode)]
# subset those with >1 per id
DT2 <- DT[, N := .N, by = id][N>1]
# create all combinations of 2
# return as a data.table with these as columns `V1` and `V2`
# then count the numbers in each group
DT2[, rbindlist(combn(featureCode,2,
FUN = function(x) as.data.table(as.list(x)), simplify = F)),
by = id][, .N, by = list(V1,V2)]
V1 V2 N
1: PPLC PCLI 3
2: PPL PPLC 1
3: PPL PCLI 1
Run Code Online (Sandbox Code Playgroud)