简体   繁体   中英

Create dyadic (relational) data from monadic data

I have conflict data that looks like this

conflict_ID country_code   SideA
1              1             1          
1              2             1 
1              3             0
2              4             1
2              5             0 

Now I want to make it into dyadic conflict data that looks like this (SideA=1 should be country_code_1 ):

conflict_ID country_code_1 country_code_2 
1              1             3          
1              2             3 
2              4             5

Can anyone point me in the right direction?

This extends the previous issue you posted. You could produce all combinations for each conflict_ID , and filter out those combinations where country_code_2 matches country_code with SideA == 1 .

library(dplyr)
library(tidyr)

mydf %>%
  group_by(conflict_ID) %>%
  summarise(country_code = combn(country_code, 2, sort, simplify = FALSE),
            .groups = 'drop') %>%
  unnest_wider(country_code, names_sep = '_') %>%
  anti_join(filter(mydf, SideA == 1),
            by = c("conflict_ID", "country_code_2" = "country_code"))

# # A tibble: 3 × 3
#   conflict_ID country_code_1 country_code_2
#         <int>          <int>          <int>
# 1           1              1              3
# 2           1              2              3
# 3           2              4              5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM