1

I just wonder if there is a way to find all subordinates of a manager. In below example, the person in p2 reports to the person in P1. I want to find all the persons report to A. If I use below code, I can get A->B A->C. But what I want is A->B A->C A->D. Is it possible?

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"])]

2 Answers2

1

There is a great anwer from joels on rstudio.com that covers your problem: https://community.rstudio.com/t/finding-all-combinations-of-parent-child-ids/24666/2

I have reproduced joels' code below:

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
zaphoid
  • 98
  • 7
0

Maybe something like the code below answers the question.

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
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66