Bfu38
Bfu38

Reputation: 1141

Remove numbers from alphanumeric characters

I have a list of alphanumeric characters that looks like:

x <-c('ACO2', 'BCKDHB456', 'CD444')

I would like the following output:

x <-c('ACO', 'BCKDHB', 'CD')

Upvotes: 63

Views: 119104

Answers (4)

Cleonidas
Cleonidas

Reputation: 179

If your goal is just to remove numbers, then the removeNumbers() function removes numbers from a text. Using it reduces the risk of mistakes.

library(tm)

x <-c('ACO2', 'BCKDHB456', 'CD444') 

x <- removeNumbers(x)

x

[1] "ACO"    "BCKDHB" "CD"    

Upvotes: 17

D Bolta
D Bolta

Reputation: 443

Using stringr

Most stringr functions handle regex

str_replace_all will do what you need

str_replace_all(c('ACO2', 'BCKDHB456', 'CD444'), "[:digit:]", "")

Upvotes: 16

altabq
altabq

Reputation: 1414

A solution using 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)

Solution in one line:

Screenshot on-liner in R

Upvotes: 6

Justin
Justin

Reputation: 43255

You can use gsub for this:

gsub('[[:digit:]]+', '', x)

or

gsub('[0-9]+', '', x)
# [1] "ACO"    "BCKDHB" "CD" 

Upvotes: 119

Related Questions