如何捕获整数(0)?

Rom*_*rik 118 error-handling integer r try-catch

假设我们有一个产生的陈述integer(0),例如

 a <- which(1:3 == 5)
Run Code Online (Sandbox Code Playgroud)

抓住这个最安全的方法是什么?

Rei*_*son 145

这是R打印零长度向量(整数1)的方式,因此您可以测试a长度为0的长度:

R> length(a)
[1] 0
Run Code Online (Sandbox Code Playgroud)

这可能是值得重新考虑你正在使用识别策略,其想要的元素,但没有进一步的具体细节,也很难提出一种替代策略.


Ric*_*ton 17

如果它是特定的零长度整数,那么你想要类似的东西

is.integer0 <- function(x)
{
  is.integer(x) && length(x) == 0L
}
Run Code Online (Sandbox Code Playgroud)

检查一下:

is.integer0(integer(0)) #TRUE
is.integer0(0L)         #FALSE
is.integer0(numeric(0)) #FALSE
Run Code Online (Sandbox Code Playgroud)

你也可以用assertive它.

library(assertive)
x <- integer(0)
assert_is_integer(x)
assert_is_empty(x)
x <- 0L
assert_is_integer(x)
assert_is_empty(x)
## Error: is_empty : x has length 1, not 0.
x <- numeric(0)
assert_is_integer(x)
assert_is_empty(x)
## Error: is_integer : x is not of class 'integer'; it has class 'numeric'.
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用`!length(x)`而不是`length(x)== 0` (3认同)
  • @詹姆士.没错,但我认为这两种方式都没有太大的性能问题,而且`length(x)== 0L`对我来说更清楚. (3认同)
  • @Ben:为数字添加一个`L`后缀使得R将它存储为整数而不是浮点值.参见,例如,http://cran.r-project.org/doc/manuals/R-lang.html#Constants (2认同)

mbq*_*mbq 12

也许偏离主题,但R具有两个漂亮,快速和空知识的功能,用于减少逻辑向量 - anyall:

if(any(x=='dolphin')) stop("Told you, no mammals!")
Run Code Online (Sandbox Code Playgroud)


42-*_*42- 7

if ( length(a <- which(1:3 == 5) ) ) print(a)  else print("nothing returned for 'a'") 
#[1] "nothing returned for 'a'"
Run Code Online (Sandbox Code Playgroud)

在第二个想法,我认为任何更美丽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'") 
Run Code Online (Sandbox Code Playgroud)


Jam*_*mes 6

受Andrie的回答启发,您可以使用identical并避免任何属性问题,因为它是该类对象的空集并将其与该类的元素组合:

attr(a,"foo")<-"bar"

> identical(1L,c(a,1L))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

或者更一般地说:

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
Run Code Online (Sandbox Code Playgroud)