我有一个类似于
的数据框mydf <- data.frame(Country=c('USA','Brazil','China','Italy','Ghana','Brazil','USA','China','USA'),
Pattern=c('XXZ','XXX','XYX','XXZ','XXX','XXX','XYZ','XXX','XYZ'),
Value=c(1,2,5,4,1,2,3,1,6))
如果 Pattern 的行相等,我需要一个无向邻接矩阵,这会增加值。
例如,
From To Pattern Value
Brazil Brazil XXX 4
Brazil China XXX 3
Brazil Ghana XXX 3
听起来你想要这个:
library(tidyverse)
mydf %>%
split(.$Pattern) %>%
map_dfr(~ .x %>%
mutate(n = row_number()) %>%
cross_join(., .) %>%
filter(n.x != n.y, Country.x <= Country.y) %>%
reframe(Value = `Value.x` + Value.y, .by = c(Country.x, Country.y)) %>%
rename(From = Country.x, To = Country.y) %>%
distinct(), .id = 'Pattern')
输出:
Pattern From To Value
1 XXX Brazil Ghana 3
2 XXX Brazil Brazil 4
3 XXX Brazil China 3
4 XXX China Ghana 2
5 XXZ Italy USA 5
6 XYZ USA USA 9