Check if a variable is a number in R

I have the following data frame:

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

I am trying to get xx from ddf using the following command:

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

How can I check if xx is a real number and not 'numeric (0)'. I tried the 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 xx = ddf[ddf$name=='a', 'value'] from different ddf data. Sometimes ddf does not contain 'a' and therefore the value is not returned. I want to discover this.

+9
source share
4 answers

The easiest way to do this using the R base is to check the length 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 example, an 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 
+9
source
 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 the class numeric ( integer also OK, since the basic check is done using is.numeric ), and secondly, it checks that the length of xx is one.

+6
source

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

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

Or if you need to deal with negative numbers and decimals:

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

How about something like this when you just check the number of rows received after filtering?

 library(tidyverse) ddf = data.frame(name=c('a','b'), value=c(10,20)) t <- ddf %>% filter(name == "c") nrow(t) == 0 [1] TRUE 
-1
source

Source: https://habr.com/ru/post/1202688/


All Articles