Home > Enterprise >  Testing whether a value is equal to a string value when it can also be NULL
Testing whether a value is equal to a string value when it can also be NULL

Time:07-07

I have a value which can be one of 3 strings, or NULL. When the value is NULL the following code does not work

value <- NULL

if( value == "test" ){
    print("1")
} else {
    print("2")
}

It seems I have to write the code as below to make it work:

if ( !is.null(value) && value== "test" ) {
    print("1")
} else {
    print("2")
}

Writing it like that however seems unnecessarily complicated and messy.

Is there a cleaner way to do this?

CodePudding user response:

You can use function setequal in base R:

value <- NULL
setequal(value, "test")
[1] FALSE

CodePudding user response:

You could surround the condition with isTRUE()

value <- NULL

if ( isTRUE(value == "test") ) {
    print("1")
} else {
    print("2")
}

# [1] "2"

or replace == with identical():

identical(value, "test")

# [1] FALSE

CodePudding user response:

How about using %in% operator:

if( "test" %in% value){
  print("1")
} else {
  print("2")
}

[1] "2"
  •  Tags:  
  • r
  • Related