Domanda

I have a network like in the diagram. In python there is the ancestors function. When i use it on node 5, it will provide list of nodes 1,2 and 3. what is an equivalent function in igraph R? I tried subcomponent but it didn't work for me.

Also my actual network is quiet long and I don't want to use parent or child function as I don't know degree in every case

enter image description here

È stato utile?

Soluzione

The R function is neighborhood with mode="in": http://igraph.org/r/doc/neighborhood.html E.g.

g1 <- graph(c(1,4, 1,2, 1,3, 3,2, 2,5))
neighborhood(g1, 5, order=vcount(g1), mode="in")[[1]]
# [1] 5 2 1 3

This will also include the queried vertex itself, but it is easy to remove that:

setdiff(neighborhood(g1, 5, order=vcount(g1), mode="in")[[1]], 5)
# [1] 2 1 3

Altri suggerimenti

Using the neighborhood function @GaborCsardi suggested, you can recursively get all the ancestors of a node:

# Warning, only works on directed graphs!
ancestors <- function(node, graph) {
  parents <- neighborhood(graph, order=1, nodes=node, mode="in")[[1]][-1]
  if (length(parents) == 0) {
    NULL
  } else {
    theirParents <- unlist(sapply(parents, ancestors, graph))
    unique(c(parents, theirParents))
  }
}

And now we can test it on your example graph:

> g1 <- graph(c(1,4, 1,2, 1,3, 3,2, 2,5))
> ancestors(5, g1)
[1] 2 1 3
> ancestors(2, g1)
[1] 1 3
> ancestors(1, g1)
NULL
> 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top