使用ifelse函数返回null

use*_*224 11 r

我试图在R中使用ifelse返回null但是它会抛出一条错误消息.有任何建议请.

这是我的代码:

cntr1 <- ifelse(unlist(gregexpr("---",path_info[j], fixed = TRUE, useBytes = TRUE)) > 0, 3 * length(unlist(gregexpr("---",path_info[j], fixed = TRUE, useBytes = TRUE))),NULL )
Run Code Online (Sandbox Code Playgroud)

错误信息是:

Error in ifelse(unlist(gregexpr("---", path_info[j], fixed = TRUE, useBytes = TRUE)) >  : 
  replacement has length zero In addition: Warning message:
In rep(no, length.out = length(ans)) :
  'x' is NULL so the result will be NULL
Run Code Online (Sandbox Code Playgroud)

And*_*ico 10

我想出了三种不同的方法来返回NULL类似ifelse的场景。

在这种情况下,b应该是NULLa是NULL

a <- NULL
is.null(a)  #TRUE

b <- switch(is.null(a)+1,"notNullHihi",NULL)
b <- if(is.null(a)) NULL else {"notNullHihi"}
b <- unlist(ifelse(is.null(a),list(NULL),"notNullHihi"))

is.null(b)  #TRUE for each of them
Run Code Online (Sandbox Code Playgroud)