Если NULL или соответствует условию, продолжайте в R - PullRequest
1 голос
/ 30 апреля 2020

Я хочу проверить, является ли x NULL / NA / NAN, и если это так, то выполнить функцию. Я также хочу выполнить функцию, если x не находится между минимальным и максимальным числом.

Если я сделаю:

#Checks if blank
isnothing <-  function(x) {
  any(is.null(x))  || any(is.na(x))  || any(is.nan(x)) 
}


x <- as.numeric(NULL)
min <- 25
max <- 45

#Actual function
if (isnothing(x) | !between(x,min,max)) {
    #Do something
}

Я получаю страшный аргумент длины ноль в Если оператор "ошибка в R

Я также пытался:

x <- as.numeric(NULL)
min <- 25
max <- 45

if (isnothing(x) |(!isnothing(x) & !between(x,min,max))) {
    #Do something
}

Это все еще не работает

---------- [РЕДАКТИРОВАТЬ] ---------

Благодаря ответу ниже у меня есть следующее:

#Checks if blank
isnothing <-  function(x) {
  any(is.null(x),is.na(x),is.nan(x))
}

y <- NULL
x <- as.numeric(y)
min <- 25
max <- 45

if (any(isnothing(y), !between(x,min,max))) {
  print("Yep")
}else{
  print("Nope")
}

Какие выходы "Да"

Работает, но выглядит грязно.

1 Ответ

2 голосов
/ 30 апреля 2020

Сочетал функцию и использовал all и any. Могут существовать лучшие способы:

isnothing <-  function(x,min, max) {
   if (all(any(is.null(x), is.na(x), is.nan(x)), between(x,min,max))) {
     print("Yep")
   }
   else{
     print("Nope")
   }

 }
 isnothing(x,min,max)
[1] "Nope"

Вариант к вышесказанному:

isnothing <-  function(x,min, max) {
   if (!any(is.null(x), is.na(x), is.nan(x))){
     if(all(between(x,min,max))) {
     print("X is between min and max")
     }
     else{
       print("X is not between min and max")
     }
   }
  else{
     print("X is null, nan or NA")
   }
   }
 isnothing(x,min,max)
[1] "X is between min and max"
 isnothing(NULL,min,max)
[1] "X is null, nan or NA"
 isnothing(55,min,max)
[1] "X is not between min and max"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...