如何使用 igraph 查找所有下属
How to find all subordinates using igraph
我就想知道有没有办法找到一个经理的所有下属。在下面的示例中,p2 中的人向 P1 中的人报告。我想找到所有向 A 报告的人。如果我使用下面的代码,我可以获得 A->B A->C。但是我想要的是A->B A->C A->D。可能吗?
d <- data.frame(p1=c('A', 'A', 'C'),
p2=c('B', 'C', 'D'))
library(igraph)
g <- graph.data.frame(d, directed=T)
print(g, e=TRUE, v=TRUE)
E(g)[from(V(g)["A"])]
也许像下面的代码这样的东西可以回答这个问题。
h <- all_simple_paths(
g,
from = "A",
to = V(g),
mode = "out"
)
if(any(lengths(h) > 2)){
h <- lapply(h, function(x) x[c(1, length(x))])
}
h
#[[1]]
#+ 2/4 vertices, named, from 17f23ba:
#[1] A C
#
#[[2]]
#+ 2/4 vertices, named, from 17f23ba:
#[1] A D
#
#[[3]]
#+ 2/4 vertices, named, from 17f23ba:
#[1] A B
joel 在 rstudio.com 上的一个很好的回答涵盖了您的问题:https://community.rstudio.com/t/finding-all-combinations-of-parent-child-ids/24666/2
我在下面复制了 joel 的代码:
library(tidyverse)
library(igraph)
d <- data.frame(p1=c('A', 'A', 'C'),
p2=c('B', 'C', 'D'))
df_g <- graph.data.frame(d, directed=T)
wanted_df = map(V(df_g), ~ names(subcomponent(df_g, .x, mode="out"))) %>%
# Convert the list output to a data frame
map_df(~data.frame(cid=.x), .id="pid") %>%
# Get rid of rows where `pid` and `cid` are equal
filter(pid != cid) %>%
filter(pid=="A")
> print(wanted_df)
pid cid
1 A C
2 A B
3 A D
我就想知道有没有办法找到一个经理的所有下属。在下面的示例中,p2 中的人向 P1 中的人报告。我想找到所有向 A 报告的人。如果我使用下面的代码,我可以获得 A->B A->C。但是我想要的是A->B A->C A->D。可能吗?
d <- data.frame(p1=c('A', 'A', 'C'),
p2=c('B', 'C', 'D'))
library(igraph)
g <- graph.data.frame(d, directed=T)
print(g, e=TRUE, v=TRUE)
E(g)[from(V(g)["A"])]
也许像下面的代码这样的东西可以回答这个问题。
h <- all_simple_paths(
g,
from = "A",
to = V(g),
mode = "out"
)
if(any(lengths(h) > 2)){
h <- lapply(h, function(x) x[c(1, length(x))])
}
h
#[[1]]
#+ 2/4 vertices, named, from 17f23ba:
#[1] A C
#
#[[2]]
#+ 2/4 vertices, named, from 17f23ba:
#[1] A D
#
#[[3]]
#+ 2/4 vertices, named, from 17f23ba:
#[1] A B
joel 在 rstudio.com 上的一个很好的回答涵盖了您的问题:https://community.rstudio.com/t/finding-all-combinations-of-parent-child-ids/24666/2
我在下面复制了 joel 的代码:
library(tidyverse)
library(igraph)
d <- data.frame(p1=c('A', 'A', 'C'),
p2=c('B', 'C', 'D'))
df_g <- graph.data.frame(d, directed=T)
wanted_df = map(V(df_g), ~ names(subcomponent(df_g, .x, mode="out"))) %>%
# Convert the list output to a data frame
map_df(~data.frame(cid=.x), .id="pid") %>%
# Get rid of rows where `pid` and `cid` are equal
filter(pid != cid) %>%
filter(pid=="A")
> print(wanted_df)
pid cid
1 A C
2 A B
3 A D