pivoting table for network analysis

Good morning,

I am trying to do network analysis, and from this table named "demo" with the relationship between people and products:

demo <- tribble(
~product_id, ~person_id,
1, 240,
1, 354,
2, 85,
2, 647,
2, 34,
)

I need to generate the following table "demo2" to get all collaborations between people who made the same product.

demo2 <- tribble(
~person_1, ~person_2,
240, 354,
85, 647,
85, 34,
647, 34,
)

Does anyone know how to do it with tidyr or base code?

Thanks in advance!

I expect there is a better way to do this but it gets to the goal.

library(tibble)
library(dplyr, warn.conflicts = FALSE)
demo <- tribble(
  ~product_id, ~person_id,
  1, 240,
  1, 354,
  2, 85,
  2, 647,
  2, 34,
)
full_join(demo, demo, by = "product_id") %>% 
  filter(person_id.x != person_id.y) %>% 
  rowwise() %>% 
  mutate(KEY = min(person_id.x, person_id.y)) %>% 
  filter(KEY == person_id.x) %>% 
  select(person_1 = person_id.x, person_2 = person_id.y)
#> # A tibble: 4 x 2
#> # Rowwise: 
#>   person_1 person_2
#>      <dbl>    <dbl>
#> 1      240      354
#> 2       85      647
#> 3       34       85
#> 4       34      647

Created on 2020-09-22 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.