Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning null using ifelse function

Tags:

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 
like image 319
user2293224 Avatar asked Aug 22 '17 10:08

user2293224


2 Answers

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 
like image 84
Andre Elrico Avatar answered Oct 14 '22 12:10

Andre Elrico


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  
like image 38
Atakan Avatar answered Oct 14 '22 13:10

Atakan