am10
am10

Reputation: 499

Converting not a Square weighted adjacency matrix to igraph object in R

I am using tf_idf value to determine similarity between webpages.Till now I have my tf_idf matrix which is not square as there are many keywords but only 36 document .I want to convert this matrix to graph object so that i can take one mode projection for the same.

So i am using this ig <- graph.adjacency(tf_idf,mode="undirected",weighted=TRUE).I want this to be weighted which is it's tf_idf value.

But,when i do this it throw an error,

Error in graph.adjacency.dense(adjmatrix, mode = mode, weighted = weighted, : not a square matrix

Can you please help me in to decide how to proceed then.

I have matrix something like this where x,y,z is keyword and A,b is webpage

mat = matrix(c(0.1, 0.5, 0.9, 0.4, 0.3, 0.5), nc=3,
           dimnames=list(c("A", "B"), c("x", "y", "z")),
           byrow=TRUE)

      x    y   z
A     0.1 0.5 0.9
B     0.4 0.3 0.5

Upvotes: 4

Views: 2978

Answers (1)

John Coleman
John Coleman

Reputation: 51998

There might be a better way, but if you want to expand your matrix to a full-fledged adjacency matrix, you can use the following function:

expand.matrix <- function(A){
  m <- nrow(A)
  n <- ncol(A)
  B <- matrix(0,nrow = m, ncol = m)
  C <- matrix(0,nrow = n, ncol = n)
  cbind(rbind(B,t(A)),rbind(A,C))
}

For example:

 A <- rbind(c(0,1,0),c(1,0,1))
> A
     [,1] [,2] [,3]
[1,]    0    1    0
[2,]    1    0    1
> expand.matrix(A)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    0
[2,]    0    0    1    0    1
[3,]    0    1    0    0    0
[4,]    1    0    0    0    0
[5,]    0    1    0    0    0

Upvotes: 1

Related Questions