2

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?

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
craszer
  • 121
  • 7

1 Answers1

4

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
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
  • I missed, that my Data has a 4th column, indicating SideA (yes=1, no=0). This needs to be incorporated into the conflict table since I do not simply want to see who was part in a conflict (status quo) but I want it to only count it as a conflict if the countries were NOT on the same side. Is there a tweak that can include that condition? – craszer Sep 16 '22 at 09:43
  • @craszer this is an extended issue of your original post. You could open a new thread to search for help. – Darren Tsai Sep 16 '22 at 10:03
  • Thanks, I opened another post. In case you are interested and might be able to help, here is the link: https://stackoverflow.com/questions/73743432/create-dyadic-data-and-count-unique-values-in-crosstable-based-on-condition – craszer Sep 16 '22 at 10:28