programing

정수(0)를 잡는 방법은?

starjava 2023. 7. 16. 12:26
반응형

정수(0)를 잡는 방법은?

예를 들어, 우리가 다음과 같은 진술을 했다고 가정해 봅시다.integer(0),예.

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

이것을 잡는 가장 안전한 방법은 무엇입니까?

이것은 길이가 0인 벡터(정수)를 인쇄하는 R의 방법입니다. 그래서 당신은 다음을 테스트할 수 있습니다.a길이가 0인 경우:

R> length(a)
[1] 0

원하는 요소를 식별하기 위해 사용 중인 전략을 다시 생각해 볼 가치가 있을 수도 있지만, 더 구체적인 세부 정보 없이는 대안 전략을 제안하기가 어렵습니다.

만약 그것이 구체적으로 0 길이 정수라면, 당신은 다음과 같은 것을 원합니다.

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'.

주제에서 벗어났을 수도 있지만, R은 논리 벡터를 줄이기 위한 두 가지 멋지고 빠르고 비어있는 인식 기능을 특징으로 합니다.any그리고.all:

if(any(x=='dolphin')) stop("Told you, no mammals!")

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
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'") 

함수가 동일한 정수(0)를 쉽게 잡을 수 있습니다(x,y).

x = integer(0)
identical(x, integer(0))
[1] TRUE

foo = function(x){identical(x, integer(0))}
foo(x)
[1] TRUE

foo(0)
[1] FALSE

또 다른 선택은rlang::is_empty(당신이 깔끔한 역에서 일하고 있다면 기억하세요)

tidyverse를 다음을 통해 연결할 때 lang 네임스페이스가 연결되지 않은 것 같습니다.library(tidyverse)이 경우 사용하는purrr::is_empty방금 에서 가져온 것입니다.rlang꾸러미

그나저나.rlang::is_empty사용자 개빈의 접근 방식을 사용합니다.

rlang::is_empty(which(1:3 == 5))
#> [1] TRUE

isEmpty()S4Vectors 기본 패키지에 포함되어 있습니다.다른 패키지를 로드할 필요가 없습니다.

a <- which(1:3 == 5)
isEmpty(a)
# [1] TRUE

언급URL : https://stackoverflow.com/questions/6451152/how-to-catch-integer0

반응형