Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R grepl to find a pure number

Tags:

regex

r

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...

like image 386
h.l.m Avatar asked Oct 26 '25 02:10

h.l.m


2 Answers

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.

like image 169
PAC Avatar answered Oct 28 '25 16:10

PAC


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

like image 24
Simon O'Hanlon Avatar answered Oct 28 '25 16:10

Simon O'Hanlon