我有一系列地址,我正在尝试用序数替换数字。现在我有以下内容。
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"
我想最终得到一个说
的向量[1] "east 1st street", "4th ave", "5th blvd", "plaza", "43rd lane"
但我无法弄清楚如何做到这一点。
答案 0 :(得分:3)
使用\\ 1,您可以在paranthesis中访问匹配表达式的一部分,但gsub不允许替换中的函数,因此您必须使用相同名称的包中的gsubfn,这实际上不需要\\ 1部分:
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)
或者,您可以使用gregexpr和regmatches来替换它们:
m <- gregexpr("[0-9]+", addlist)
regmatches(addlist, m) <- sapply(as.integer(regmatches(addlist,m)), toOrdinary)