59

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')
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
Bfu38
  • 1,081
  • 1
  • 8
  • 17

4 Answers4

113

You can use gsub for this:

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

or

gsub('[0-9]+', '', x)
# [1] "ACO"    "BCKDHB" "CD" 
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Justin
  • 42,475
  • 9
  • 93
  • 111
16

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"    
AndrewGB
  • 16,126
  • 5
  • 18
  • 49
Cleonidas
  • 169
  • 1
  • 3
  • 2
    Please format your answer and provide information about how your answer is better than the ones that were already posted. Also: Just code usually isn't enough. Can you explain what your solution does? – Noel Widmer May 31 '17 at 19:27
15

Using stringr

Most stringr functions handle regex

str_replace_all will do what you need

str_replace_all(c('ACO2', 'BCKDHB456', 'CD444'), "[:digit:]", "")
D Bolta
  • 423
  • 3
  • 8
6

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

Jaap
  • 81,064
  • 34
  • 182
  • 193
altabq
  • 1,322
  • 1
  • 20
  • 33
  • Is a nice solution, however I have state names with footnotes (that I want to remove) and by "District of Columbia" I get three character values instead of one. Due to this my output vector is much longer than my input vector. Ideas how to fix this? – N.Varela Feb 24 '17 at 21:22
  • You could use [this solution](http://stackoverflow.com/a/5412122/2254210), which is going to work for every state but DC, because it's not a state. You'd have to add DC to the `state.abb` and `state.name` vectors manually. – altabq Feb 25 '17 at 16:50