Checking if a variable is a number in R

The following code uses regular expressions to confirm that the character string on contains numeric digits and has at least a single digit. See below:

grepl("^[0-9]{1,}$", xx)

Or if you need to deal with negative numbers and decimal places:

grepl("^[-]{0,1}[0-9]{0,}.{0,1}[0-9]{1,}$", xx)

library(assertive)
is_a_number(xx)          # returns TRUE or FALSE
assert_is_a_number(xx)   # throws an error if not TRUE

This combines two tests. Firstly it checks that xx has class numeric (integer is OK too, since the underlying check is done by is.numeric), and secondly it checks that the length of xx is one.


The easiest way to do this using base R is to check the length of xx.

if(length(xx)>0)
  {
  <do something>
  }

If you want to check that the variable is also numeric use is.numeric

if (length(xx)>0 & is.numeric(xx))

For instance, taking your example:

xx <- ddf[ddf$name=='a','value']

is.numeric(xx) & length(xx)>0
[1] TRUE


xx <- ddf[ddf$name=='c','value']

is.numeric(xx) & length(xx)>0
[1] FALSE


xx <- ddf[ddf$name=='a','name']

is.numeric(xx) & length(xx)>0
[1] FALSE

Tags:

R