''
is an empty character. It does not mean “completely empty” – that is indeed NULL
.
To test for it, just check for equality:
if (variable == '') …
However, the error you’re getting,
missing value where TRUE/FALSE needed
means that there’s a missing value in your variable, i.e. NA
. if
cannot deal with missing values. 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.