如果为NULL或满足条件,则在R中继续

时间:2020-04-30 11:11:52

标签: r if-statement null

我想检查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中出现可怕的“ if语句中参数长度为零”错误

我也尝试过:

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 个答案:

答案 0 :(得分:2)

结合了功能,并使用了allany。可能存在更好的方法:

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"