rtidyversedata-wranglingtidy

How to split String column right justified into multiple columns in R?


I have a dataset contains a column like this:

dput(df[1:20, 8]) %>% structure()

 [1] "TASBUDAK-EREGLI (KONYA)"           
 [2] "HANCAGIZ-SAMANDAG (HATAY)"         
 [3] "SOGUT-DOGANSEHIR (MALATYA)"        
 [4] "KUCUKLU-DOGANSEHIR (MALATYA)"      
 [5] "KEMALPASA-GOKSUN (KAHRAMANMARAS)"  
 [6] "ULUKOY-(MALATYA)"                  
 [7] "KAZANLIPINAR-(KAHRAMANMARAS)"      
 [8] "ULUBAHCE-PAZARCIK (KAHRAMANMARAS)" 
 [9] "EMIRLER-NURDAGI (GAZIANTEP)"       
[10] "CELIKKOY-GOLBASI (ADIYAMAN)"       
[11] "KAZANDERE-GOKSUN (KAHRAMANMARAS)"  
[12] "BESCI-EMIRGAZI (KONYA)"            
[13] "ORDEKDEDE-PAZARCIK (KAHRAMANMARAS)"
[14] "CAVUSLU-DOGANSEHIR (MALATYA)"      
[15] "KULLAR-NURHAK (KAHRAMANMARAS)"     
[16] "IZCI-SURUC (SANLIURFA)"            
[17] "YAZIKOY-AFSIN (KAHRAMANMARAS)"     
[18] "DEMIRCI-EMIRGAZI (KONYA)"          
[19] "ORTULU-LICE (DIYARBAKIR)"          
[20] "KAMISTAS-(MALATYA)"

I want to separate this column into three columns with the code below:

df %>% 
  separate(Region, 
           into = c("Suburb", "Town", "City"))

and the result is that:

Suburb Town City
KAZANDERE GÖKSUN KAHRAMANMARAS
DOGU AKDENIZ NA NA
ISIKLI YESILYURT MALATYA
COBANTASI BINGOL NA
GOKSUN KAHRAMANMARAS NA
YAGMURLU GOKSUN KAHRAMANMARAS

But i want to split this columns with a right justified order like that:

Suburb Town City
KAZANDERE GÖKSUN KAHRAMANMARAS
NA NA DOGU AKDENIZ
ISIKLI YESILYURT MALATYA
NA COBANTASI BINGOL
NA GOKSUN KAHRAMANMARAS
YAGMURLU GOKSUN KAHRAMANMARAS

How can I do that?


Solution

  • df %>% 
      separate(Region, into = c("Suburb", "Town", "City"), fill = 'left')
    

    should do the trick