假设我们有一个产生integer(0)
的陈述,例如
a <- which(1:3 == 5)
最安全的方法是什么?
答案 0 :(得分:136)
这是R打印零长度向量(整数1)的方式,因此您可以测试长度为0的a
:
R> length(a)
[1] 0
您可能需要重新考虑用于识别所需元素的策略,但如果没有进一步的具体细节,则很难提出替代策略。
答案 1 :(得分:17)
如果它的长度整数特别为零,则需要类似
的内容is.integer0 <- function(x)
{
is.integer(x) && length(x) == 0L
}
检查:
is.integer0(integer(0)) #TRUE
is.integer0(0L) #FALSE
is.integer0(numeric(0)) #FALSE
您也可以使用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'.
答案 2 :(得分:12)
可能偏离主题,但R具有两个漂亮,快速且空白的功能,用于减少逻辑向量 - any
和all
:
if(any(x=='dolphin')) stop("Told you, no mammals!")
答案 3 :(得分:7)
if ( length(a <- which(1:3 == 5) ) ) print(a) else print("nothing returned for 'a'")
#[1] "nothing returned for 'a'"
我想第二个想法比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'")
答案 4 :(得分:5)
受Andrie的回答启发,您可以使用identical
并通过使用它是该类对象的空集合并将其与该类的元素组合来避免任何属性问题:
attr(a,"foo")<-"bar"
> identical(1L,c(a,1L))
[1] TRUE
或更一般地说:
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 :(得分:1)
您可以使用功能相同的(x,y)轻松捕获整数(0)
g++ Main.cpp -o main.exe -lgdi32 -lopengl32 -lglfw3dll -lglu32 -pthread -Wall -Wextra
答案 6 :(得分:1)
另一个选项是 rlang::is_empty
(如果您在 tidyverse 中工作,则很有用)
通过 library(tidyverse)
附加 tidyverse 时似乎没有附加 rlang 命名空间 - 在这种情况下,您使用 purrr::is_empty
,它只是从 rlang
包中导入。
顺便说一下,rlang::is_empty
使用了 user Gavin's approach。
rlang::is_empty(which(1:3 == 5))
#> [1] TRUE
答案 7 :(得分:0)
isEmpty()
包含在S4Vectors基本软件包中。无需加载其他任何软件包。
a <- which(1:3 == 5)
isEmpty(a)
# [1] TRUE