R - How to test for character(0) in IF statement R - How to test for character(0) in IF statement r r

R - How to test for character(0) in IF statement


Use the identical function to check this.

a <- character(0)identical(a, character(0))  # returns TRUEidentical(a, "")           # returns FALSEidentical(a, numeric(0))   # returns also FALSE


Adding the obligatory tidyverse answer. The rlang package has the function is_empty(), which does exactly what you want.

Test <- character(0)rlang::is_empty(Test)#[1] TRUE

This also works for empty vectors that aren't characters. For example, it works in the case that Patrick Roocks describes in comments.

Test <- as.Date(character(0))rlang::is_empty(Test)#[1] TRUE

Loading the 'tidyverse' package also loads is_empty().


Use the length() method:

> check <- function(value) {+ if (length(value)==0) {+ print('Empty')+ } else {+ print('Not Empty')+ }+ }> check("Hello World")[1] "Not Empty"> check("")[1] "Not Empty"> check(character(0))[1] "Empty"