Question

I have created a random (Erdos-Renyi) graph with p = 0.2 and 10 nodes in R using the igraph package like this:

library(igraph)
graph <- erdos.renyi.game(10, 0.2, type = c("gnp", "gnm"), directed = FALSE,
    loops = FALSE)

I find the central node and leaf nodes of the graph like this:

centralNode <- which(degree(graph) %in% c(max(degree(graph))))
leafNodes <- which(degree(graph) %in% c(1))

I find the shortest path from the central node to the first leaf node like this:

sp <- get.shortest.paths(graph, centralNode, leafNodes[1])

And can get something like this (if 1 is the centralNode and 4 is the leafNodes[1]:

[[1]]
[1] 1  2  9  4

I want to be able to access each of the vertices in the shortest path from the centralNode to the leafNodes[1].

I tried doing it like this but keep getting these errors:

sp$2
    Error: unexpected numeric constant in "sp$2"
sp$[[1]][2]
    Error: unexpected '[[' in "sp$[["
sp$1[2]
    Error: unexpected numeric constant in "sp$1"
sp$[1][2]
    Error: unexpected '[' in "sp$["

I'm not sure how to return each vertex individually, or just pick one of them. I hope this makes sense.

Any help would be much appreciated. Thanks

Was it helpful?

Solution

sp is just a standard list. So sp[[1]] etc will work to just get a vector.

However, it probably makes more sense for you to be subsetting the graph object. Something like this:

V(graph)[sp[[1]]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top