Check if the variable has a value ''

In a script, I try to run, sometimes the variables are populated with '' (which means: completely empty), e.g.

 variable <- '' 

Does anyone know of a method for checking if a variable has a value? ''

is.null(variable) does not seem to work. '' does not match NULL .

+11
string r
source share
3 answers

'' is an empty character. This does not mean "completely empty" - it is really NULL .

To verify this, simply check for equality:

 if (variable == '') … 

If you want to check if a variable exists, you need to use ... exists :

 if (exists('variable')) … 

But in fact, in normal code there are very few cases of using exists , since, as the author of the code, you should know which variables exist and which do not. Rather, it is primarily useful in library functions.

However, the error you get is

missing value requiring TRUE / FALSE

does not mean that the variable does not exist. Rather, if cannot deal with missing values ​​- i.e. NA . NA is the result of many calculations that themselves contain the value NA . For example, comparing NA with any value (even NA ) again gives NA :

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

Since if expects TRUE or FALSE , it cannot deal with NA . If you have a chance that your values ​​may be NA , you need to check this explicitly:

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

However, as a rule, it is best to exclude NA values ​​from your data from get-go so that they do not propagate in such a situation, as indicated above.

+19
source share

The stringi package has a function for this.

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

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

+3
source share

If you want to check and replace these values ​​with NA at the same time, as usual, just use dplyr::na_if() :

 variable <- '' dplyr::na_if(variable, "") #> [1] NA 
0
source share

All Articles