Splitting column by separator from right to left in R

醉酒当歌 提交于 2019-11-28 10:38:07

问题


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") 

回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/46717210/splitting-column-by-separator-from-right-to-left-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!