Home > Back-end >  Reformat a street address
Reformat a street address

Time:12-23

I have the the address of a property that is split into a number of fields. For properties that are flats (apartments) the street name and number is not ideally formed to match to other information:

Address1 <- c("76", "Flat 2", "Flat 4")
Address2 <- c("Acacia Avenue", "Hightown, 23", "London Road, 34A")

# Not ideal for flats
print(paste(Address1, Address2))

Address3 < -c("Acacia Avenue", "23, Hightown", "34A, London Road")
# Better for flats
print(paste(Address1, Address3))

what I would like is to move the property "number" from the end of the street name to the beginning.

The rule I feel is some thing like:

looking at the end of the string:

is there a ", " followed by a number or a number plus a single character?
if so then move the contents after the "," to the start of the string.

CodePudding user response:

Here an example:

Address2 <- c("Acacia Avenue", "Hightown, 23", "London Road, 34A", "Flat 2")
gsub("(.*), (\\d [A-Za-z]?$)" ,"\\2 \\1", Address2)
#> [1] "Acacia Avenue"   "23 Hightown"     "34A London Road" "Flat 2"
  • Related