r - 将 DataFrame 转换为 R 中的邻接/权重矩阵
问题描述
我有一个数据框,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
我想将此 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
解决方案
这是一个非常粗糙且可能非常低效的解决方案,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()
推荐阅读
- python - 从 tkinter 中的变量获取检查按钮的文本
- java - 如何嵌入经纪人?缺少 broker.xml
- apache - Ubuntu“无法重新启动 apache2.service:未找到单元 apache2.service。”
- android - 如何为 AlertDialog 设置自定义布局?
- python - 在pandas中groupby之后将多列转换为dict
- c# - 在没有着色器的 Unity 上将 YUV420P 转换为 JPEG
- cakephp - 尽管使用安全组件解锁操作,为什么 AJAX 请求会触发 400 响应?
- angular - Angular - 映射到 API 响应中的返回实体
- javascript - 这是您在 csharp 中正确编码 html textarea 的方式吗
- rxjs - 放置 HTMLElement 时 fromEvent 不会触发,放置 Jquery 对象时不会触发