view raw
Moose Moose - 7 months ago 84
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
to specify the first and last characters.

How can I go about this?


you can try

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