regex - Splitting column by separator from right to left in R


Keywords:r 


Question: 

I'm working on a dataset where one column (Place) consists of a location sentence.

librabry(tidyverse)  

example <- tibble(Datum = c("October 1st 2017", 
                            "October 2st 2017",
                            "October 3rd 2017"),
             Place = c("Tabiyyah Jazeera village, 20km south east of Deir Ezzor, Deir Ezzor Governorate, Syria",
                       "Abu Kamal, Deir Ezzor Governorate, Syria",
                       "شارع القطار al Qitar [train] street, al-Tawassiya area, north of Raqqah city centre, Raqqah governorate, Syria"))

I would like to split the Place column by the comma separator so I prefer a solution with the tidyverse package. Because the values of Place have different lengths I would like to start from right to left. So that the country Syria is the value in the last column of this dataframe.

Oh, and for a bonus with which RegEx code do I delete the Arabic characters?

Thanks in advance.

Edit: Found my answer: For removing Arabic characters (thanks to @g5w):

gsub("[\u0600-\u06FF]", "", airstrikes_okt_clean$Plek)

And splitting the column in a tidyr way:

airstrikes_okt_clean <- separate(example, 
                             Place, 
                             into = c("detail", 
                                      "detail2", 
                                      "City_or_village", 
                                      "District", 
                                      "Country"), 
                             sep = ",", 
                             fill = "left") 

2 Answers: 

Just split the string on comma and the reverse it.

 lapply(strsplit(Place, ","), rev)
[[1]]
[1] " Syria"                         " Deir Ezzor Governorate"       
[3] " 20km south east of Deir Ezzor" "Tabiyyah Jazeera village"      

[[2]]
[1] " Syria"                  " Deir Ezzor Governorate"
[3] "Abu Kamal"              

[[3]]
[1] " Syria"                              " Raqqah governorate"                
[3] " north of Raqqah city centre"        " al-Tawassiya area"                 
[5] "شارع القطار al Qitar [train] street"

To get rid of the Arabic characters before splitting, try

gsub("[\u0600-\u06FF]", "", Place)
[1] "Tabiyyah Jazeera village, 20km south east of Deir Ezzor, Deir Ezzor Governorate, Syria"              
[2] "Abu Kamal, Deir Ezzor Governorate, Syria"                                                            
[3] "  al Qitar [train] street, al-Tawassiya area, north of Raqqah city centre, Raqqah governorate, Syria"
 

Here's a one-liner.

sapply(strsplit(example$Place, ","), function(x) trimws(x[length(x)]))

It will return the string after the last comma, be it Syria or any other.