Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a variable is a number in R

Tags:

r

I have following data frame:

> ddf = data.frame(name=c('a','b'), value=c(10,20))
> ddf
  name value
1    a    10
2    b    20

I try to get xx from ddf using following command:

> xx = ddf[ddf$name=='a','value']
> xx
[1] 10
> xx = ddf[ddf$name=='c','value']
> xx
numeric(0)

How can I test if xx is a valid number and not 'numeric(0)'. I tried following:

> is.numeric(xx)
[1] TRUE
> is.na(xx)
logical(0)
> is.null(xx)
[1] FALSE
> is.logical(xx)
[1] FALSE

I have to ask for xx = ddf[ddf$name=='a', 'value'] from different ddf data frames. Sometimes ddf does not contain 'a' and hence no value is returned. I want to detect this.

like image 961
rnso Avatar asked Sep 16 '14 14:09

rnso


People also ask

How do I check if a variable is numeric in R?

We can check if our vector is numeric by using the function is. numeric() . We can check our data type by using the functions class() and typeof() . class() tells us that we're working with numeric values, while typeof() is more specific and tells us we're working with doubles (i.e., numbers with decimals).

How do you check if a column is a number in R?

We can use select_if() function to get numeric columns by calling the function with the dataframe name and isnumeric() function that will check for numeric columns.

How do I identify a variable in R?

A variable in R can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number.


2 Answers

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
like image 114
nico Avatar answered Oct 26 '22 14:10

nico


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)
like image 23
BillZ Avatar answered Oct 26 '22 13:10

BillZ