在R中将DataFrame转换为邻接/权重矩阵

Ric*_*loo 7 r matrix adjacency-matrix

我有一个DataFrame , df.

n是一列,表示列中的组数x.
x是包含逗号分隔组的列.

df <- data.frame(n = c(2, 3, 2, 2), 
                 x = c("a, b", "a, c, d", "c, d", "d, b"))

> df
n        x
2     a, b
3  a, c, d
2     c, d
2     d, b
Run Code Online (Sandbox Code Playgroud)

我想将此DataFrame转换为权重矩阵,其中行和列名称是组中的唯一值,df$x元素表示每个组一起出现的次数df$x.

输出应如下所示:

m <- matrix(c(0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 2, 1, 1, 2, 0), nrow = 4, ncol = 4)
rownames(m) <- letters[1:4]; colnames(m) <- letters[1:4]

> m
  a b c d
a 0 1 1 1
b 1 0 0 1
c 1 0 0 2
d 1 1 2 0
Run Code Online (Sandbox Code Playgroud)

Dan*_*cks 5

这是一个非常粗略,可能非常低效的解决方案,tidyverse用于争论和combinat生成排列.

library(tidyverse)
library(combinat)

df <- data.frame(n = c(2, 3, 2, 2), 
                 x = c("a, b", "a, c, d", "c, d", "d, b"))

df %>% 
    ## Parse entries in x into distinct elements
    mutate(split = map(x, str_split, pattern = ', '), 
           flat = flatten(split)) %>% 
    ## Construct 2-element subsets of each set of elements
    mutate(combn = map(flat, combn, 2, simplify = FALSE)) %>% 
    unnest(combn) %>% 
    ## Construct permutations of the 2-element subsets
    mutate(perm = map(combn, permn)) %>% 
    unnest(perm) %>% 
    ## Parse the permutations into row and column indices
    mutate(row = map_chr(perm, 1), 
           col = map_chr(perm, 2)) %>% 
    count(row, col) %>% 
    ## Long to wide representation
    spread(key = col, value = nn, fill = 0) %>% 
    ## Coerce to matrix
    column_to_rownames(var = 'row') %>% 
    as.matrix()
Run Code Online (Sandbox Code Playgroud)


Ony*_*mbu 5

使用Base R,您可以执行以下操作

a = strsplit(as.character(df$x),', ')
b = unique(unlist(a))
d = unlist(sapply(a,combn,2,toString))
e = data.frame(table(factor(d,c(paste(b,b,sep=','),combn(b,2,toString)))))
f = read.table(text = do.call(paste,c(sep =',', e)),sep=',',strip.white = T)
g = xtabs(V3~V1+V2,f)
g[lower.tri(g)] = t(g)[lower.tri(g)]
g
   V2
V1  a b c d
  a 0 1 1 1
  b 1 0 0 0
  c 1 0 0 2
  d 1 0 2 0
Run Code Online (Sandbox Code Playgroud)