我有一个字母数字字符列表,如下所示:
x <-c('ACO2', 'BCKDHB456', 'CD444')
Run Code Online (Sandbox Code Playgroud)
我想要以下输出:
x <-c('ACO', 'BCKDHB', 'CD')
Run Code Online (Sandbox Code Playgroud)
有什么建议?
# dput(tmp2)
structure(c(432L, 326L, 217L, 371L, 179L, 182L, 188L, 268L, 255L,..., 
), class = "factor")
Run Code Online (Sandbox Code Playgroud)
    Jus*_*tin 68
你可以使用gsub这个:
gsub('[[:digit:]]+', '', x)
Run Code Online (Sandbox Code Playgroud)
要么
gsub('[0-9]+', '', x)
# [1] "ACO"    "BCKDHB" "CD" 
Run Code Online (Sandbox Code Playgroud)
        小智 11
如果您的目标只是删除数字,则该removeNumbers()函数会从文本中删除数字。使用它可以降低出错的风险。
library(tm)
x <-c('ACO2', 'BCKDHB456', 'CD444') 
x <- removeNumbers(x)
x
[1] "ACO"    "BCKDHB" "CD"    
Run Code Online (Sandbox Code Playgroud)
        使用字符串
大多数字符串函数处理正则表达式
str_replace_all会做你需要的
str_replace_all(c('ACO2', 'BCKDHB456', 'CD444'), "[:digit:]", "")
Run Code Online (Sandbox Code Playgroud)
        使用stringi的解决方案:
# your data
x <-c('ACO2', 'BCKDHB456', 'CD444')
# extract capital letters
x <- stri_extract_all_regex(x, "[A-Z]+")
# unlist, so that you have a vector
x <- unlist(x)
Run Code Online (Sandbox Code Playgroud)
一行解决方案:
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           45269 次  |  
        
|   最近记录:  |