user2293224
user2293224

Reputation: 2220

returning null using ifelse function

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

Upvotes: 30

Views: 15782

Answers (4)

Kevin Chen
Kevin Chen

Reputation: 91

use switch() rather than ifelse() if you want to return NULL

reference:
https://www.r-bloggers.com/2017/02/use-switch-instead-of-ifelse-to-return-a-null/

Upvotes: 2

Atakan
Atakan

Reputation: 446

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

Upvotes: 4

Andre Elrico
Andre Elrico

Reputation: 11480

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

Upvotes: 23

cryo111
cryo111

Reputation: 4474

In your specific case, where yes and no of ifelse are single-element vectors, you can try to return the results as lists

ifelse(c(TRUE,FALSE,TRUE),list(1),list(NULL))
#[[1]]
#[1] 1
#
#[[2]]
#NULL
#
#[[3]]
#[1] 1

This approach would also work if either of yes or no are multi-element lists. See for instance

x=as.list(1:3)
y=c(as.list(letters[1:2]),list(NULL))
ifelse(x<2,x,y)
#[[1]]
#[1] 1
#
#[[2]]
#[1] "b"
#
#[[3]]
#NULL

Upvotes: 1

Related Questions