'How do I combine reciprocal vertices in a network graph

I have the vertices for a network graph going in both directions but they aren't actually directional. I want to combine them so that, in the example below, df0 becomes df1. "Bob and Krishna" is the same as "Krishna and Bob." I feel there must be a more clever approach than a brute force for loop test. How should I do this? Thans.

df0 <- data.frame(n1 = c("bob","krishna","mary"),
              n2=c("krishna","bob","bob"),
              w=c(1,2,3))
df0
#>        n1      n2 w
#> 1     bob krishna 1
#> 2 krishna     bob 2
#> 3    mary     bob 3

df1 <- data.frame(n1 = c("bob","mary"),
             n2=c("krishna","bob"),
             w=c(3,3))
df1
#>     n1      n2 w
#> 1  bob krishna 3
#> 2 mary     bob 3

Here is a dplyr version of the accepted answer:

df0 %>%
  rowwise() %>%
  mutate(n12 = list(sort(c(n1, n2)))) %>%
  mutate(n1 = n12[1]) %>%
  mutate(n2 = n12[2]) %>%
  select(-person12)
r


Solution 1:[1]

You can sort the rows (so that krishna bob becomes bob krishna) and then aggregate the results.

f0[,1:2] = t(apply(f0[,1:2], 1, sort))
aggregate(f0$w, f0[,1:2], sum)
   n1      n2 x
1 bob krishna 3
2 bob    mary 3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 G5W