将data.frame转换为邻接矩阵(R)

时间:2019-05-17 12:46:40

标签: r dataframe matrix network-programming

我想将data.frame转换为邻接矩阵。在我的数据中,我得到了文章和作者(几列,每个共同作者一个),其中每一行都是一篇文章。我希望把同一篇文章的作者绑在一起。

数据结构现在是这样的:

data <- data.frame(Author1 = c("Alan", "Rebecca", "Micheal", "Dany", "Euron", "Alan"),
                   Author2 = c("Rebecca", NA, "Alan", "Euron", NA, "Dany"),
                   Author3 = c("Dany", NA, "Euron", "Micheal", NA, NA),
                   Author4 = c("Euron", NA, "Rebecca", NA, NA, NA),
                   Title = c("Eric's boat", "Top 100 boats", "Boats in the World", "Death and boats", "Boats and Dragons", "Boats"))

哪个给出以下输出:

+---------+---------+---------+---------+--------------------+
| Author 1| Author2 | Author3 | Author4 | Title              |
+---------+---------+---------+---------+--------------------+
| Alan    | Rebecca | Dany    | Euron   | Eric's boat        |
| Rebecca | NA      | NA      | NA      | Top 100 boats      |
| Micheal | Alan    | Euron   | Rebecca | Boats in the world |
| Dany    | Euron   | Micheal | NA      | Death and boats    |
| Euron   | NA      | NA      | NA      | Boats and Dragons  |
| Alan    | Dany    | NA      | NA      | Boats              |
+---------+---------+---------+---------+--------------------+

我希望它看起来像这样:

+---------+------+---------+---------+------+-------+
|         | Alan | Rebecca | Micheal | Dany | Euron |
+---------+------+---------+---------+------+-------+
| Alan    |    0 |       1 |       0 |    1 |     1 |
| Rebecca |    1 |       0 |       1 |    0 |     0 |
| Micheal |    1 |       1 |       1 |    1 |     1 |
| Dany    |    1 |       0 |       1 |    0 |     1 |
| Euron   |    1 |       0 |       1 |    1 |     0 |
+---------+------+---------+---------+------+-------+

0 个答案:

没有答案