简体   繁体   中英

Removing characters after space in a string - R Studio data cleaning

I am attempting to clean some data in R Studio.

Here's an example of my data.

LSOA name:
York 009A
Wychavon 014A
Bath and North East Somerset 001A
Aylesbury Vale 008C
Central Bedfordshire 030C

I want to be able to remove the code from the end of each. So that the resulting data looks like this:

LSOA name:
York
Wychavon
Bath and North East Somerset
Aylesbury Vale 
Central Bedfordshire 

I am quite new to regex so finding this quite difficult. From what I can tell, as there is a variable number of words before the code, a simple remove characters after a whitespace is not possible.

Any help would be hugely appreciated!

We can use sub to match one or more spaces followed by one or more digits ( \\d+ ) and an upper case letter ( [AZ] ) at the end ( $ ) of the string and replace it with blank ( "" )

df1$name <- sub("\\s+\\d+[A-Z]$", "", df1$name)

-output

df1
#                          name
#1                         York
#2                     Wychavon
#3 Bath and North East Somerset
#4               Aylesbury Vale
#5         Central Bedfordshire

data

df1 <- structure(list(name = c("York 009A", "Wychavon 014A", 
"Bath and North East Somerset 001A", 
"Aylesbury Vale 008C", "Central Bedfordshire 030C")), class = "data.frame",
row.names = c(NA, 
-5L))

You can also use lookahead (?=\\s\\d+) and backreference \\1 :

sub("(.*)(?=\\s\\d+).*", "\\1", df1$name, perl = T)
[1] "York"                         "Wychavon"                     "Bath and North East Somerset" "Aylesbury Vale"              
[5] "Central Bedfordshire"

Another option is str_extract and the nagative character class \\D , which matches any char that is not a digit ( trimws removes the whitespace).

library(stringr)
trimws(str_extract(df1$name, "\\D+"))

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