Moose Moose - 2 months ago 29
R Question

Extract letters from a string in R

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?

Answer

you can try

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