0

I have a dataset with 4 variables, month, country, event_type and n, as below and event_type includes 6 different factors. I want to convert them to variables as new columns and each variable should include the n. Any guidance is much appreciated!

month       country     event_type  n
Apr-2018    Afghanistan Battles 1648
Apr-2018    Afghanistan Explosions/Remote violence  683
Apr-2018    Afghanistan Protests    30
Apr-2018    Afghanistan Riots   2
Apr-2018    Afghanistan Strategic developments  31
Apr-2018    Afghanistan Violence against civilians  44
Apr-2018    Colombia    Battles 90
Apr-2018    Colombia    Explosions/Remote violence  20
Apr-2018    Colombia    Protests    7
Apr-2018    Colombia    Strategic developments  64
Apr-2018    Colombia    Violence against civilians  148
Apr-2018    India   Battles 152
Apr-2018    India   Explosions/Remote violence  50
Apr-2018    India   Protests    1347
Apr-2018    India   Riots   592
Apr-2018    India   Strategic developments  18

For instance;

Month     Country     Battle Explosions..  Protests Riots Strategic development
Apr-2018  Afghanistan 1648   683           30       2     31

1 Answers1

2

Starting from this subset:

> print(data)
# A tibble: 6 x 4
  month    country     event_type                     n
  <chr>    <chr>       <chr>                      <dbl>
1 Apr-2018 Afghanistan Battles                     1648
2 Apr-2018 Afghanistan Explosions/Remote violence   683
3 Apr-2018 Afghanistan Protests                      30
4 Apr-2018 Afghanistan Riots                          2
5 Apr-2018 Afghanistan Strategic developments        31
6 Apr-2018 Afghanistan Violence against civilians    44

Use pivot_wider

library(tidyverse)    
data_wide <- data %>% pivot_wider(names_from = event_type, values_from = n)

Which returns:

> print(data_wide)
# A tibble: 1 x 8
  month    country     Battles `Explosions/Remote violence` Protests Riots `Strategic developments` `Violence against civilians`
  <chr>    <chr>         <dbl>                        <dbl>    <dbl> <dbl>                    <dbl>                        <dbl>
1 Apr-2018 Afghanistan    1648                          683       30     2                       31                           44
ornaldo_
  • 125
  • 6
  • many thanks, that works. Also, how can ı create a new variable from month data. I want to have seperate colums as months and years. @ornaldo_ – Ümit Seven Mar 29 '21 at 19:07
  • @ÜmitSeven `separate(month, c("month", "year"), sep = "-")`. You're welcome. – ornaldo_ Mar 29 '21 at 19:12