Using toOrdinal to replace numbers with ordinals

I have a sequence of addresses and I am trying to replace numbers with ordinals. 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 in the end to get a vector that says

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

      

but I can't figure out how to do it.

+3


source to share


1 answer


With \\ 1, you can access the part of the matching expression in paranthesis, but gsub does not allow functions in replacement, so you have to use gsubfn from the package with the same name, which you don't really 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)

      

+3


source







All Articles