循环遍历数据框:计算每个唯一变量的值的每个成对组合.

tdm*_*996 3 combinations loops r dataframe

我有一个名为"df"的数据框,如下所示:

ID  Value
1   a
1   b
1   c
1   d
3   a
3   b
3   e
3   f
.   .
.   .
.   .
Run Code Online (Sandbox Code Playgroud)

我有一个填充零的矩阵,如下所示:

  a b c d e f 
a x 0 0 0 0 0
b 0 x 0 0 0 0
c 0 0 x 0 0 0
d 0 0 0 x 0 0
e 0 0 0 0 x 0
f 0 0 0 0 0 x
Run Code Online (Sandbox Code Playgroud)

然后我想循环数据框这样的事情:

for each ID, for each value i, for each value j != i, matrix[i,j] += 1 
Run Code Online (Sandbox Code Playgroud)

因此,对于每个ID,对于每个值的组合,我想将矩阵中的值提高1,从而导致:

  a b c d e f 
a x 2 1 1 1 1
b 2 x 1 1 1 1
c 1 1 x 1 0 0
d 1 1 1 x 0 0
e 1 1 0 0 x 1
f 1 1 0 0 1 x
Run Code Online (Sandbox Code Playgroud)

因此,例如,[a,b] = 2,因为这两个值的组合出现在两个不同的ID中,而[a,c] = 1,因为这种值组合仅在ID = 1时发生,而在ID = 3时不发生.

我怎样才能做到这一点?我已经制作了一个包含唯一ID的向量.

提前致谢.

akr*_*run 5

最简单的是获得table然后做一个crossprod

out <- crossprod(table(df))
diag(out) <- NA #replace the diagonals with NA
names(dimnames(out)) <- NULL #set the names of the dimnames as NULL
out
#   a  b  c  d  e  f
#a NA  2  1  1  1  1
#b  2 NA  1  1  1  1
#c  1  1 NA  1  0  0
#d  1  1  1 NA  0  0
#e  1  1  0  0 NA  1
#f  1  1  0  0  1 NA
Run Code Online (Sandbox Code Playgroud)

数据

df <- structure(list(ID = c(1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L), Value = c("a", 
"b", "c", "d", "a", "b", "e", "f")), .Names = c("ID", "Value"
 ), class = "data.frame", row.names = c(NA, -8L))
Run Code Online (Sandbox Code Playgroud)