我有一个向量如下所示:
t <- c("8466 W Peoria Ave", "4250 W Anthem Way", .....)
我想将它转换为:
t_mod <-c("Peoria Ave", "Anthem Way".....)
我想从字符串向量中删除数字和单个字符。
非常感谢您的帮助。
tt <- c("8466 W Peoria Ave", "4250 W Anthem Way")
gsub(" [A-Za-z] ", "", gsub("[0-9]", "", tt))
[1] "Peoria Ave" "Anthem Way"
这是你要的:
# Data
t <- c("8466 W Peoria Ave", "4250 W Anthem Way")
# Remove numbers and split by whitespace
t.char <- sub("[[:alnum:]]* ", "", t)
t.char.split <- strsplit(t.char, " ")
# Remove strings with only one character
t.mod <- sapply(t.char.split, function(i) {
paste(i[which(nchar(i) > 1)], collapse = " ")
})
t.mod
[1] "Peoria Ave" "Anthem Way"
我不太擅长正则表达式,但我可以尝试一下,这样怎么样:
t_mod <- gsub("^[0-9]{1,} [a-z][A-Z] ", "", t)
t_mod
[1] "Peoria Ave" "Anthem Way"
char <- c("8466 W Peoria Ave", "4250 W Anthem Way")
gsub("[[:digit:]]+ *[[:alpha:]].","",char)
#[1] "Peoria Ave" "Anthem Way"
t
作为变量名。 - user1609452