R:邻接矩阵的邻接列表
您好,我想将邻接列表(3列)转换为邻接矩阵。在这个论坛中,我找到了多个关于如何将边列表转换为邻接矩阵的示例。我成功地为两列列表完成了这项工作。 我已经尝试了在网络上找到的所有解决方案,但似乎我错过了一小步 我试过的 我的变量是用户、国家、书籍R:邻接矩阵的邻接列表,r,matrix,igraph,adjacency-list,adjacency-matrix,R,Matrix,Igraph,Adjacency List,Adjacency Matrix,您好,我想将邻接列表(3列)转换为邻接矩阵。在这个论坛中,我找到了多个关于如何将边列表转换为邻接矩阵的示例。我成功地为两列列表完成了这项工作。 我已经尝试了在网络上找到的所有解决方案,但似乎我错过了一小步 我试过的 我的变量是用户、国家、书籍 User<-c("maman","sophia","Antoine") Country<-c("Canada","USA","Mexico") books<-c("Coelho","Rimbaud","The flight")
User<-c("maman","sophia","Antoine")
Country<-c("Canada","USA","Mexico")
books<-c("Coelho","Rimbaud","The flight")
dat<-data.frame(User, Country,books)
User | Country | books
maman | Canada | Coelho
sophia| USA | Rimbaud
Antoine| Mexico | The flight
我想看看所有顶点之间的相互作用。类似于此:
任何帮助或指示都将不胜感激 也许这就是你想要的:
m <- as.matrix(dat)
el <- cbind(m[, 1], c(m[, -1]))
现在,我们可以通过使用graph.edgelist
绘制边列表并使用get.adjacence
提取邻接矩阵来获得邻接矩阵
get.adjacency(graph.edgelist(el))
## 9 x 9 sparse Matrix of class "dgCMatrix"
## maman Canada sophia USA Antoine Mexico Coelho Rimbaud The flight
## maman . 1 . . . . 1 . .
## Canada . . . . . . . . .
## sophia . . . 1 . . . 1 .
## USA . . . . . . . . .
## Antoine . . . . . 1 . . 1
## Mexico . . . . . . . . .
## Coelho . . . . . . . . .
## Rimbaud . . . . . . . . .
## The flight . . . . . . . . .
完美的它正在工作:)我也想了解你的代码。你能从graph.edgelist(……)解释一下吗?我只是在行数超过三行时尝试过,但它不会生成矩阵。有没有办法创建一个邻接矩阵?@Shean10000-下面这个5x3矩阵的例子对我很有用:
m@Shean10000-我现在把事情弄得更清楚了。我已经试过用这个矩阵m:m
maman sophia Antoine Canada USA Mexico Coelho Rimbaud The fligth
maman 1 0 1 0 0 0 0 1 0
sophia 0 0 0 0 1 0 1 0 1
Antoine 0 1 1 0 1 0 0 1 0
Canada 1 0 1 0 0 1 0 1 1
USA 0 0 0 1 0 0 0 0 1
Mexico 0 0 0 0 1 1 1 0 0
Coelho 0 0 1 1 0 1 0 1 0
Rimbaud 1 0 1 1 0 0 0 1 1
The fligth 0 1 0 0 1 1 0 0 1
m <- as.matrix(dat)
el <- cbind(m[, 1], c(m[, -1]))
el
## [,1] [,2]
## [1,] "maman" "Canada"
## [2,] "sophia" "USA"
## [3,] "Antoine" "Mexico"
## [4,] "maman" "Coelho"
## [5,] "sophia" "Rimbaud"
## [6,] "Antoine" "The flight"
get.adjacency(graph.edgelist(el))
## 9 x 9 sparse Matrix of class "dgCMatrix"
## maman Canada sophia USA Antoine Mexico Coelho Rimbaud The flight
## maman . 1 . . . . 1 . .
## Canada . . . . . . . . .
## sophia . . . 1 . . . 1 .
## USA . . . . . . . . .
## Antoine . . . . . 1 . . 1
## Mexico . . . . . . . . .
## Coelho . . . . . . . . .
## Rimbaud . . . . . . . . .
## The flight . . . . . . . . .