从字符串中删除特定的模式

3

我有一个向量如下所示:

t <- c("8466 W Peoria Ave", "4250 W Anthem Way", .....)

我想将它转换为:
t_mod <-c("Peoria Ave", "Anthem Way".....)

我想从字符串向量中删除数字和单个字符。

非常感谢您的帮助。


你可以使用R中的正则表达式(http://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html)通过调用grep函数来修复你的t向量...删除单个字符:(http://stackoverflow.com/questions/10306312/regex-to-remove-single-characters-from-string)...删除数字:(https://dev59.com/u3A75IYBdhLWcg3wUHOQ) - Teemu Daniel Laajala
最好不要将t作为变量名。 - user1609452
4个回答

4
tt <- c("8466 W Peoria Ave", "4250 W Anthem Way")
gsub(" [A-Za-z] ", "", gsub("[0-9]", "", tt))
[1] "Peoria Ave" "Anthem Way"

1

这是你要的:

# 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"

1

我不太擅长正则表达式,但我可以尝试一下,这样怎么样:

t_mod <- gsub("^[0-9]{1,} [a-z][A-Z] ", "", t)

这将首先剥离字符串开头的任意数量数字,接着是一个空格,任何字母,然后再是一个空格。然后我的t_mod看起来就像你需要的:
t_mod
[1] "Peoria Ave" "Anthem Way"

0
char <- c("8466 W Peoria Ave", "4250 W Anthem Way")
gsub("[[:digit:]]+ *[[:alpha:]].","",char)
#[1] "Peoria Ave" "Anthem Way"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接