I am trying to return null using ifelse in R. But it throws an error message. Any suggestion please.
Here is my code:
cntr1 <- ifelse(unlist(gregexpr("---",path_info[j], fixed = TRUE, useBytes = TRUE)) > 0, 3 * length(unlist(gregexpr("---",path_info[j], fixed = TRUE, useBytes = TRUE))),NULL )
Error message is:
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
I came up with three different approaches to return NULL
in an ifelse-like scenario.
In this scenario b should be NULL
when a is 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
I needed a similar functionality in one of my recent applications. This is how I came up with a solution.
obj <- "val1" # Override a with null (this fails) newobj <- ifelse(a == "val1", NULL, a) # Separating the ifelse statement to if and else works if(obj == "val1") newobj <- NULL else newobj <- obj
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With