Home > Software engineering >  Group by intersecting vectors
Group by intersecting vectors

Time:04-09

Consider this tibble:

tibble(id = list(c(1, 2), c(3, 4, 7), c(3, 5), 10, c(5, 6)))

  id       
  <list>   
1 <dbl [2]>
2 <dbl [3]>
3 <dbl [2]>
4 <dbl [1]>
5 <dbl [2]>

I'd like to group id if one or more value in one row is also in another row. Here, the first row is 1 2 and neither 1 nor 2 appear in other rows, it is then the only one assigned group == 1. Same with row 4. Row 2, 3 and 5 share digit 3 (for row 2 and 3) and digit 5 (row 3 and 5), they are then all assigned to the same group.

Expected output:

# A tibble: 5 x 2
  id        group
  <list>    <dbl>
1 <dbl [2]>     1
2 <dbl [3]>     2
3 <dbl [2]>     2
4 <dbl [1]>     3
5 <dbl [2]>     2

Any ideas on how to do this? maybe igraph?

CodePudding user response:

library(tidyverse)
library(igraph)

df %>%
  mutate(rn = paste0('node', row_number()))%>%
  left_join(unnest(., id) %>%
              graph_from_data_frame(dir = FALSE) %>% 
              components() %>%
              getElement('membership')%>%
              enframe('rn', 'group'))

# A tibble: 5 x 3
  id        rn    group
  <list>    <chr> <dbl>
1 <dbl [2]> node1     1
2 <dbl [3]> node2     2
3 <dbl [2]> node3     2
4 <dbl [1]> node4     3
5 <dbl [2]> node5     2
  • Related