How to catch an integer (0)?

Say we have an instruction that produces integer(0) , for example.

  a <- which(1:3 == 5) 

What is the safest way to catch this?

+80
integer r try-catch error-handling
Jun 23 '11 at 8:18
source share
5 answers

This is an R-way to print a zero-length vector (integer), so you can check that a has a length of 0:

 R> length(a) [1] 0 

It might be worth reviewing the strategy you are using to determine which elements you want, but without additional specific details it is difficult to suggest an alternative strategy.

+103
Jun 23 '11 at 8:30
source share

If these are integers with zero length, you need something like

 is.integer0 <- function(x) { is.integer(x) && length(x) == 0L } 

Check it out with

 is.integer0(integer(0)) #TRUE is.integer0(0L) #FALSE is.integer0(numeric(0)) #FALSE 
+12
Jun 23 2018-11-11T00:
source share

Probably off topic, but R has two nice, fast and empty functions for reducing logical vectors - any and all :

 if(any(x=='dolphin')) stop("Told you, no mammals!") 
+10
Jun 23 2018-11-11T00:
source share
 if ( length(a <- which(1:3 == 5) ) ) print(a) else print("nothing returned for 'a'") #[1] "nothing returned for 'a'" 

In a second thought, I think that anyone is more beautiful than length(.) :

  if ( any(a <- which(1:3 == 5) ) ) print(a) else print("nothing returned for 'a'") if ( any(a <- 1:3 == 5 ) ) print(a) else print("nothing returned for 'a'") 
+7
June 42-23 2018-11-11T00:
source share

Inspired by Andry, you can use identical and avoid any problems with attributes, using the fact that it is an empty set of this object class and combine it with an element of this class:

 attr(a,"foo")<-"bar" > identical(1L,c(a,1L)) [1] TRUE 

Or more generally:

 is.empty <- function(x, mode=NULL){ if (is.null(mode)) mode <- class(x) identical(vector(mode,1),c(x,vector(class(x),1))) } b <- numeric(0) > is.empty(a) [1] TRUE > is.empty(a,"numeric") [1] FALSE > is.empty(b) [1] TRUE > is.empty(b,"integer") [1] FALSE 
+5
Jun 23 '11 at 11:11
source share



All Articles