简体   繁体   中英

Drop a word in a column of data table in R

I have a data table that looks like

            location                county
1:  40.96875_-72.78125      Walla Walla County
2:  41.15625_-90.65625           Mercer County
3:  41.21875_-90.65625           Mercer County
4:  41.28125_-89.84375           Bureau County
5:  41.28125_-89.90625            Henry County

How can I, efficiently, drop the word "county" in the county column, so, only the name of counties is left in there.

We can use sub to select one or more spaces followed by characters that are not a space until the end ( $ ) of the string, replace with blanks ( "" )

dt1[, county := sub("\\s+[^ ]+$", "", county)]
dt1$county
#[1] "Walla Walla" "Mercer"      "Mercer"      "Bureau"      "Henry"      

If it is specific to 'County' word, then

dt1[, county := sub("\\s+County$", "", county)]

或者,您可以使用 de gsub函数,将单词"county"替换为""

df$county = gsub("county", "", df$county)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM