首页 > 解决方案 > 使用 igraph 包的邻接矩阵

问题描述

我使用igraphpackage inR进行社交网络分析。我决定使用,当我想使用邻接矩阵时Movielens Dataset (Movies Section),我还加载了。igraph Library

数据集加载成功,这些是我的代码。

ff = read.csv("D:/TMU/DataSet/MovieLens/movies.csv", header = TRUE)
ff
mtr = as.matrix(ff)
gr = graph.adjacency(mtr, mode = "undirected", weighted = NULL, diag = FALSE)

我遇到了这个错误:

graph.adjacency.dense 中的错误(adjmatrix,模式 = 模式,加权 = 加权,:
在 structure_generators.c:274:非方阵,非方阵
另外:警告消息:
在 mde(x)中:NAs 引入强迫

数据集有问题还是什么?

标签: rgraphigraphadjacency-matrix

解决方案


好的,使用来自https://grouplens.org/datasets/movielens/的小数据集,其尺寸为 9125x3

下载数据(如果您使用mode的是 Windows,则可能需要调整)download.file

pth <- "http://files.grouplens.org/datasets/movielens/ml-latest-small.zip"
download.file(pth, destfile=temp<-tempfile())
#unzip(temp, list=TRUE) # see what files?
unzip(temp, exdir=td<-tempdir()) 

# read movies dataset
movies <- read.csv(file.path(td, "ml-latest-small/movies.csv"), 
                   header=TRUE, stringsAsFactors = FALSE)

加载一些库

library(tm) # to form the binary matrix: best to keep things sparse
library(slam) # for the crossproduct of the simple_triplet_matrix returned by tm::DocumentTermMatrix
library(igraph) 

按流派为电影形成二进制矩阵(必须使用 MrFlick 对 VCorpus 的建议,否则“(未列出流派)”和“黑色电影”被分成单独的词

# split the genres string and create binary matrix for presence of genre
corp <- VCorpus(VectorSource(movies$genres))
dtm <- DocumentTermMatrix(corp, 
                          control = list(tokenize = function(x) 
                            unlist(strsplit(as.character(x), "\\|"))))

创建邻接矩阵

# this looks for agreement across the genres
# you could use tcrossprod for similarities on the films
adj <- crossprod_simple_triplet_matrix(dtm)

创建图表

g <- graph_from_adjacency_matrix(adj, mode="undirected", weighted=TRUE)

推荐阅读