0

In the network and sna packages, is there a way to ensure that you reliably access nodes by an arbitrary id/name, and return output using this id/name? It appears that, even if vertex names are explicitly assigned, the packages default to using 1:n integer indexing of nodes, and I at least cannot find a way to access the internal index. This is seen in the following example:

library(network)
library(sna)
set.seed(12345)
m<-matrix(rbinom(100,1,0.02),10)
diag(m) <- 0
m.sna <- as.network.matrix(m, directed = T)
network.vertex.names(m.sna) <- letters[1:10]

#note that there is a tie between 3,7 or c,g
get.neighborhood(m.sna,"c", type = "combined") # this fails to return node g/7 as part of node c's neighborhood
get.neighborhood(m.sna,3, type = "combined") # this correctly returns the node

The first attempt to return the neighborhood of node g/7 using the explicit vertex name fails to return its neighbor (node c/3). The second attempt succeeds using an index (based the row of the original matrix). However this index does not seem to be an explicit node attribute. Is there a way to gain more control over how nodes are indexed?

tvg
  • 388
  • 2
  • 13

1 Answers1

1

You have to use vertex indices, but you can get those via attributes.

You can get the "vertex.names" attribute values like so:

get.vertex.attribute(m.sna, "vertex.names")
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

But that's can get a bit verbose, so you can use the %v% infix instead:

m.sna %v% "vertex.names"
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

You can then use == to figure out which values equal your desired vertex's name:

m.sna %v% "vertex.names" == "c"
#>  [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

Which you can wrap in which() to get that vertex's index:

which(m.sna %v% "vertex.names" == "c")
#> [1] 3

Putting it all together gives you the following:

get.neighborhood(m.sna, 
                 v = which(m.sna %v% "vertex.names" == "c"), 
                 type = "combined")
#> [1] 7
knapply
  • 647
  • 1
  • 5
  • 11