1

I'm working with networks like these:

mat1 network diagram

mat1 <- matrix(
  c(
    -1, -1, -1, 0, 0,
    1, -1, -1, 0, 0,
    1, 1, 0, -1, -1,
    0, 0, 1, -1, 0,
    0, 0, 1, 0, -1
  ),
  nrow = 5, ncol = 5, byrow = TRUE, 
  dimnames = list(NULL, c("N1", "N2", "A2", "Z3", "M"))
)

I'm trying to get all the loops into a dataframe broken into node pathways that form a loop like this:

out <- data.frame(
  from = c("N2", "N2", "Z3"),
  to = c("A2", "A2", "A2"),
  to1 = c("N2", "N1", "Z3"),
  to2 = c(NA, "N2", NA))

I've asked a similar question identifying pathways from specific nodes

but this is about extracting loops from the whole model regardless of which node you start with. The order isn't important so for example Z3 to A2 to Z3 is the same loop as A2 to Z3 to A2.

I'm very new to igraph, but I'm imagining that I would need something akin to:

lapply(V(g)[degree(g, mode = "out", loops = TRUE) > 0]

which was suggested in a comment on my previous post, but I'm unsure

1

1 Answer 1

0

Given matrix mat1, you can try the code below

mat1 %>%
  `<`(0) %>%
  graph_from_adjacency_matrix(
    mode = "directed"
  ) %>%
  as_data_frame() %>%
  mutate(id = row_number(), .by = from) %>%
  pivot_wider(
    names_from = id,
    names_glue = "to{id}",
    values_from = to
  )

which gives

# A tibble: 5 × 4
  from  to1   to2   to3  
  <chr> <chr> <chr> <chr>
1 N1    N1    N2    A2
2 N2    N2    A2    NA
3 A2    Z3    M     NA
4 Z3    Z3    NA    NA
5 M     M     NA    NA

If you care the vertices that have loops only, you can try

mat1 %>%
  `<`(0) %>%
  graph_from_adjacency_matrix(
    mode = "directed"
  ) %>%
  as_data_frame() %>%
  filter(from %in% {
    filter(., from == to) %>% pull(from)
  }) %>%
  mutate(id = row_number(), .by = from) %>%
  pivot_wider(
    names_from = id,
    names_glue = "to{id}",
    values_from = to
  )

such that

# A tibble: 4 × 4
  from  to1   to2   to3  
  <chr> <chr> <chr> <chr>
1 N1    N1    N2    A2
2 N2    N2    A2    NA
3 Z3    Z3    NA    NA
4 M     M     NA    NA
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.