Probably a very basic question but its buggging me that i can't easily find a solution...so i thought i should come to the wisdom of the SO wise ones...
I would like to be able to return a TRUE or FALSE acording to if a character string is a pure number rather than just containing numbers... The closest I got was
grepl("[0-9]","99393")
grepl("[0-9]","blah")
However this doesn't work since the following is returned as TRUE when it should be FALSE
grepl("[0-9]","993T3")
As ever any help would be appreciated!
EDIT
As joran pointed out it is important to note that the character string will only ever include integers and letters, i.e. will not include decimal points or commas for the number...
You should specify the whole regular expression and specify the beginning (^) and the end of the string ($). For instance :
> grepl("^[[:digit:]]+$","993T3")
[1] FALSE
Look at http://en.wikibooks.org/wiki/R_Programming/Text_Processing#Regular_Expressions if you want to learn more about regexp.
Why don't you just use robust internal methods for coercing to either an integer or numeric?
It will return NA if it can't be done. Use is.na if you want a logical result:
is.na( as.integer( "993T3" ) )
# [1] TRUE
is.na( as.integer( "99393" ) )
# [1] FALSE
Remember that if you are dealing with floating point numbers use as.numeric otherwise you will truncate the floating point part of your number using as.integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With