Moose Moose - 1 year ago 135
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?

Answer Source

you can try

sub("^([[:alpha:]]*).*", "\\1", x)
[1] "AB"  "GF"  "ABC"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download