Home > front end >  How to convert monadic data in to dyadic (relational) data
How to convert monadic data in to dyadic (relational) data

Time:09-15

I have conflict data sorted by a conflict ID that looks like this:

conflict_ID country_code
1              1
1              2
1              3 
2              1
3              31
2              50 
3              3 

I want to make this data dyadic so I will end up with this:

conflict_ID country_code_1 country_code_2 
1              1             2          
1              1             3 
1              2             3
2              1             50
3              3             31 

I have searched the forum and found the following code which I think goes in the right direction, but I can't get it to work.

mydf %>% 
    group_by(conflict_ID) %>%
    mutate(ind= paste0('country_code', row_number())) %>% 
    spread(ind, country_code)

Can anyone point me in the right direction?

CodePudding user response:

You could summarise each conflict_ID with combn() and unnest the combinations to multiple columns.

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 = '_')

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