[R] Check if string has all alphabets or numbers
jim holtman
jholtman at gmail.com
Mon Nov 23 21:00:35 CET 2009
Here is the way you can use grepl to get the various combinations:
> mywords<- c("harry","met","sally","subway10","1800Movies","12345",
+ "not correct 123", "")
>
> numbers <- grepl("^[[:digit:]]+$", mywords)
> letters <- grepl("^[[:alpha:]]+$", mywords)
> both <- grepl("^[[:digit:][:alpha:]]+$", mywords)
>
> mywords[letters]
[1] "harry" "met" "sally"
> mywords[numbers]
[1] "12345"
> mywords[xor((letters | numbers), both)] # letters & numbers mixed
[1] "subway10" "1800Movies"
>
>
On Mon, Nov 23, 2009 at 9:17 AM, hadley wickham <h.wickham at gmail.com> wrote:
>>> 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)
>
> mywords<- c("harry","met","sally","subway10","1800Movies","12345",
> "not correct 123", "")
> mywords[grepl("^[[:digit:][:alpha:]]*$", mywords)]
>
> So maybe you should use
>
> mywords[grepl("^[[:digit:][:alpha:]]+$", mywords)]
>
>
> And grepl is highly recommended over grep.
>
> Hadley
>
> --
> http://had.co.nz/
>
--
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