using toOrdinal to replace numbers with ordinals

229 Views Asked by At

I have a sequence of addresses and I am trying to replace numbers with ordinals. Right now I have the following.

library(toOrdinal)
addlist<-c("east 1 street", "4 ave", "5 blvd", "plaza", "43 lane" )
numstringc<-gsub("\\D", "", addlist)
numstring <-as.integer(numstringc)
ordstring<-sapply(numstring[!is.na(numstring)], toOrdinal)
ordstring
[1] "1st"  "4th"  "5th"  "43rd"

I want to eventually get a vector that says

[1] "east 1st street", "4th ave", "5th blvd", "plaza", "43rd lane"

but I can't figure out how to make that.

1

There are 1 best solutions below

0
On

With \\1 you can access the part of the matched expression in paranthesis, but gsub doesn't allow functions in the replacement, so you have to use gsubfn from the package by the same name, which actually doesn't need the \\1 part:

library(gsubfn)
addlist<-c("east 1 street", "4 ave", "5 blvd", "plaza", "43 lane" )
ordstring <- gsubfn("[0-9]+", function (x) toOrdinal(as.integer(x)), addlist)

Alternatively you can use gregexpr and regmatches, to replace them:

m <- gregexpr("[0-9]+", addlist)
regmatches(addlist, m) <- sapply(as.integer(regmatches(addlist,m)), toOrdinary)