Check if variable has the value ''

'' is an empty character. It does not mean “completely empty” – that is indeed NULL.

To test for it, just check for equality:

if (variable == '') …

If you want to check whether a variable exists, you need to use … exists:

if (exists('variable')) …

But in fact there are very few use-cases for exists in normal code, since as the author of the code you should know which variables exist and which don’t. Rather, it’s primarily useful in library functions.

However, the error you’re getting,

missing value where TRUE/FALSE needed

does not mean that the variable doesn’t exist. Rather, if cannot deal with missing values – i.e. NA. An NA occurs as a result of many computations which themselves contain an NA value. For instance, comparing NA to any value (even NA itself) again yields NA:

variable = NA
variable == NA
# [1] NA

Since if expects TRUE or FALSE, it cannot deal with NA. If there’s a chance that your values can be NA, you need to check for this explicitly:

if (is.na(variable) || variable == '') …

However, it’s normally a better idea to exclude NA values from your data from the get-go, so that they shouldn’t propagate into a situation like the above.


In stringi package there is function for this.

require(stringi)    
stri_isempty(c("A","")) 

You can also install this package from github: https://github.com/Rexamine/stringi

Tags:

String

R