【发布时间】:2021-09-22 20:44:34
【问题描述】:
我有一个类似这样的数据框:
| case_id | pol_demo | pol_demo_online | pol_post_online | pol_petition | pol_cntct_polit | pol_party | pol_other | pol_demo_illegal |
|---|---|---|---|---|---|---|---|---|
| 1311 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| 97 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 5480 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 2531 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| 2291 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
| 2064 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
case_id 对应于调查对象的唯一 id,它的唯一值与数据框中的行数一样多。列是行为形式,相应的受访者做了 (1) 或没有做 (0)。列数比图片上的多 (17),但您明白了。
我想将其转换为邻接矩阵。也就是说,我想要一个有 17 行和 17 列的矩阵(每个行为一个),并且单元格应该是组合不同形式的行为的次数(每对的总和)。因此,使用示例中的列,矩阵将如下所示:
| pol_demo | pol_demo_online | pol_post_online | pol_petition | pol_cntct_polit | pol_party | pol_other | pol_demo_illegal | |
|---|---|---|---|---|---|---|---|---|
| pol_demo | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 |
| pol_demo_online | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 |
| pol_post_online | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 |
| pol_petition | 3 | 3 | 3 | 4 | 3 | 3 | 3 | 2 |
| pol_cntct_polit | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 |
| pol_party | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 |
| pol_other | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 2 |
| pol_demo_illegal | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |
意思是pol_demo与pol_demo_online结合3次,而与pol_demo_illegal等只有2次。
我有一种预感,我需要与outer 合作,但我想不通。我会很高兴有一个整洁的解决方案,但真的,非常感谢任何帮助!
这是数据的sn-p:
dat <- structure(list(pol_demo = c(1, 0, 0, 1, 0, 1), pol_demo_online = c(1,
0, 0, 1, 0, 1), pol_post_online = c(1, 0, 0, 1, 0, 1), pol_petition = c(1,
0, 0, 1, 1, 1), pol_cntct_polit = c(1, 0, 0, 1, 0, 1), pol_party = c(1,
0, 0, 1, 0, 1), pol_other = c(1, 0, 0, 1, 0, 1), pol_demo_illegal = c(0,
0, 0, 1, 0, 1), help_shopping = c(1, 1, 0, 1, 1, 1), help_childcare = c(0,
1, 0, 1, 0, 1), help_general = c(1, 1, 0, 1, 1, 1), help_emo = c(1,
1, 0, 1, 1, 1), help_symb = c(1, 1, 0, 1, 0, 1), help_fin = c(1,
0, 0, 1, 1, 1), help_donation = c(1, 0, 0, 1, 1, 1), help_volunteer = c(1,
0, 0, 1, 0, 1), help_other = c(1, 1, 0, 1, 0, 1), case_id = structure(c(1311,
97, 548, 2531, 2291, 2064), label = "numerical, unique ID per respondent", format.stata = "%9.0g")), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
【问题讨论】:
标签: r tidyverse adjacency-matrix