rigraphsocial-networkingsna

R, error in finding degree, closeness and betweenness


Trying to apply the common measures of centrality to a simple data set of non-directed like this:

enter image description here

It gives error:

Error in closeness(net, gmode = "graph") : unused argument (gmode = "graph")

When I removed the argument (gmode = "graph), it gives:

Error in degree(W) : Not a graph object 

I have tried to use this lines to convert them, but still doesn't work:

W <- graph_from_adjacency_matrix(df)
W <- graph_from_data_frame(df)

How can I correct them? thank you.

Here are the lines:

Bob <- c(0,1,0,0,0)
Kate <- c(0,0,0,1,0)
David <- c(0,0,0,1,0)
Jack <- c(0,0,1,0,0)
Peter <- c(0,1,0,0,1)
df <- data.frame(Bob, Kate, David, Jack, Peter)

library(igraph)

W <- data.frame(df)
net <- network(W)

net %v% 'vertex.names'

degree(W, gmode="graph")
closeness(net, gmode="graph")
betweenness(net, gmode="graph")

Add-on after this question is answered, in case it can help someone - to convert Excel format into a adjacency_matrix, use below lines.

df <- readxl::read_excel("spreadsheet.xlsx", sheet = "Sheet1")
W <- as.matrix(df)
W <- graph_from_adjacency_matrix(W)

Solution

  • Your code is somewhat mysterious, suggesting perhaps a use of of some other package? There is no such function network in igraph, functions degree, closeness, and betweenness don't have argument gmode. I believe the following is what you were after:

    library(igraph)
    # We are going to use graph_from_adjacency_matrix, so we need a matrix
    # rather than a data frame
    df <- cbind(Bob, Kate, David, Jack, Peter)
    
    W <- graph_from_adjacency_matrix(df)
    
    V(W)$name
    # [1] "Bob"   "Kate"  "David" "Jack"  "Peter"
    
    degree(W)
    #   Bob  Kate David  Jack Peter 
    #     1     3     2     3     3 
    closeness(W)
    #        Bob       Kate      David       Jack      Peter 
    # 0.05000000 0.08333333 0.11111111 0.16666667 0.05000000 
    # Warning message:
    # In closeness(W) :
    #   At centrality.c:2784 :closeness centrality is not well-defined for disconnected graphs
    betweenness(W)
    #   Bob  Kate David  Jack Peter 
    #     0     4     0     3     0