Extract letters from a string in R

我的未来我决定 提交于 2019-12-01 14:31:18

问题


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?


回答1:


you can try

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



回答2:


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" 



回答3:


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"




回答4:


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 = " ")



回答5:


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!



来源:https://stackoverflow.com/questions/30912199/extract-letters-from-a-string-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!