[R] test if elements of a character vector contain letters

Liviu Andronic landronimirc at gmail.com
Mon Aug 6 23:55:18 CEST 2012


On Mon, Aug 6, 2012 at 7:35 PM, Marc Schwartz <marc_schwartz at me.com> wrote:
> is.letter <- function(x) grepl("[[:alpha:]]", x)
> is.number <- function(x) grepl("[[:digit:]]", x)
>


This does exactly what I wanted:
> x
 [1] "a10" "b8"  "c9"  "d2"  "e3"  "f4"  "g1"  "h7"  "i6"  "j5"  "k"
"l"   "m"   "n"
[15] "o"   "p"   "q"   "r"   "s"   "t"   "u"   "v"   "w"   "x"   "y"
"z"   "1"   "2"
[29] "3"   "4"   "5"   "6"   "7"   "8"   "9"   "10"  "11"  "12"  "13"
"14"  "15"  "16"
[43] "17"  "18"  "19"  "20"  "21"  "22"  "23"  "24"  "25"  "26"
> xb <- grepl("[[:alpha:]]",x)
> x[xb]  ##extract all vector elements that contain a letter
 [1] "a10" "b8"  "c9"  "d2"  "e3"  "f4"  "g1"  "h7"  "i6"  "j5"  "k"
"l"   "m"   "n"
[15] "o"   "p"   "q"   "r"   "s"   "t"   "u"   "v"   "w"   "x"   "y"   "z"
> xb <- grepl("[[:digit:]]",x)
> x[xb]  ##extract all vector elements that contain a digit
 [1] "a10" "b8"  "c9"  "d2"  "e3"  "f4"  "g1"  "h7"  "i6"  "j5"  "1"
"2"   "3"   "4"
[15] "5"   "6"   "7"   "8"   "9"   "10"  "11"  "12"  "13"  "14"  "15"
"16"  "17"  "18"
[29] "19"  "20"  "21"  "22"  "23"  "24"  "25"  "26"

Thanks all for the suggestions! Regards
Liviu



More information about the R-help mailing list