Reputation: 275
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?
Upvotes: 17
Views: 48615
Reputation: 165
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"
Upvotes: 16
Reputation: 21
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!
Upvotes: 2
Reputation: 1906
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 = " ")
Upvotes: 3
Reputation: 9976
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"
Upvotes: 2
Reputation: 5314
you can try
sub("^([[:alpha:]]*).*", "\\1", x)
[1] "AB" "GF" "ABC"
Upvotes: 11