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

Liviu Andronic landronimirc at gmail.com
Tue Aug 7 22:02:47 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)
>

Another follow-up. To test for (non-)alphanumeric one would do the following:
> x <- c(letters, 1:26, '+', '-', '%^&')
> x[1:10] <- paste(x[1:10], 1:10, sep='')
> x
 [1] "a1"  "b2"  "c3"  "d4"  "e5"  "f6"  "g7"  "h8"  "i9"  "j10" "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("[[:alnum:]]",x)  ##test for alphanumeric chars
> x[xb]
 [1] "a1"  "b2"  "c3"  "d4"  "e5"  "f6"  "g7"  "h8"  "i9"  "j10" "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("[[:punct:]]",x)  ##test for non-alphanumeric chars
> x[xb]
[1] "+"   "-"   "%^&"


More regex rules are available on the Wiki [1]. Regards
Liviu

[1] http://en.wikipedia.org/wiki/Regular_expression



More information about the R-help mailing list