[R] Check if string has all alphabets or numbers

jim holtman jholtman at gmail.com
Mon Nov 23 14:38:21 CET 2009


Added a little more:

> mywords<- c("harry","met","sally","subway10","1800Movies","12345", "not correct 123")
> all.letters <- grep("^[[:alpha:]]*$", mywords)
> all.numbers <- grep("^[[:digit:]]*$", mywords)  # numbers
> mixed <- grep("^[[:digit:][:alpha:]]*$", mywords)
> all.letters
[1] 1 2 3
> all.numbers
[1] 6
> # mixed
> setdiff(mixed, c(all.numbers, all.letters))
[1] 4 5
> # not any of the above
> setdiff(seq(length(mywords)), c(mixed, all.numbers, all.letters))
[1] 7
>


On Mon, Nov 23, 2009 at 8:28 AM, Harsh <singhalblr at gmail.com> wrote:
> Hi R users,
> I'd like to know if anyone has come across problems wherein it was necessary
> to check if strings contained all alphabets, some numbers or all numbers?
>
> In my attempt to test if a string is numeric, alpha-numeric (also includes
> if string is only alphabets) :
>
> # Reproducible R code below
> mywords<- c("harry","met","sally","subway10","1800Movies","12345")
>
> mywords.alphanum
> <-lapply(sapply(mywords,function(x)strsplit(x,NULL)),function(y)
> ifelse(sum(is.na(sapply(y,as.numeric))) == 0 & length(y) >
> 0,"numeric","alpha-numeric"))
>
> names(mywords.alphanum)[(which(mywords.alphanum == "numeric"))]
>
>
> I understand that such "one-liners"  (the second line of code above) that
> make multiple calls are discouraged, but I seem to find then fascinating.
>
> Looking forward to alternate solutions/packages  for the above problem.
>
> Thanks
> Harsh Singhal
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list