Extract letters from a string in R

45.6k views Asked by At

I have a character vector containing variable names such as x <- c("AB.38.2", "GF.40.4", "ABC.34.2"). I want to extract the letters so that I have a character vector now containing only the letters e.g. c("AB", "GF", "ABC").

Because the number of letters varies, I cannot use substring to specify the first and last characters.

How can I go about this?

5

There are 5 answers

3
Mamoun Benghezal On BEST ANSWER

you can try

sub("^([[:alpha:]]*).*", "\\1", x)
[1] "AB"  "GF"  "ABC"
0
centaur On

I realize this is an old question but since I was looking for a similar answer just now and found it, I thought I'd share.

The simplest and fastest solution I found myself:

x <- c("AB.38.2", "GF.40.4", "ABC.34.2")
only_letters <- function(x) { gsub("^([[:alpha:]]*).*$","\\1",x) }
only_letters(x)

And the output is:

[1] "AB"  "GF"  "ABC"

Hope this helps someone!

0
Bernard Beckerman On

The previous answers seem more complicated than necessary. This question regarding digits also works with letters:

> x <- c("AB.38.2", "GF.40.4", "ABC.34.2", "A B ..C 312, Fd", "  a")
> gsub("[^a-zA-Z]", "", x)
[1] "AB"    "GF"    "ABC"   "ABCFd" "a" 
0
mimoralea On

None of the answers work if you have mixed letter with spaces. Here is what I'm doing for those cases:

x <- c("AB.38.2", "GF.40.4", "ABC.34.2", "A B ..C 312, Fd")
unique(na.omit(unlist(strsplit(unlist(x), "[^a-zA-Z]+"))))

[1] "AB" "GF" "ABC" "A" "B" "C" "Fd"

1
cephalopod On

This is how I managed to solve this problem. I use this because it returns the 5 items cleanly and I can control if i want a space in between the words:

x <- c("AB.38.2", "GF.40.4", "ABC.34.2", "A B ..C 312, Fd", "  a")

extract.alpha <- function(x, space = ""){      
  require(stringr)
  require(purrr)
  require(magrittr)
  
  y <- strsplit(unlist(x), "[^a-zA-Z]+") 
  z <- y %>% map(~paste(., collapse = space)) %>% simplify()
  return(z)}

extract.alpha(x, space = " ")