R - How to test for character(0) in IF statement
I imagine this is incredibly simple but I cant seem to find the answer.
I am writing an IF statement but the test is if the object returns a character(0)
value. I am not sure how to deal with character(0)
in the statement.
Assuming Test <- character(0)
or a value:
if (identical(Pols4,character(0))) {
print('Empty')
} else {
print('Not Empty')
}
It still does not seem to work.....
Solution 1:
Use the identical
function to check this.
a <- character(0)
identical(a, character(0)) # returns TRUE
identical(a, "") # returns FALSE
identical(a, numeric(0)) # returns also FALSE
Solution 2:
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()
.
Solution 3:
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"
Solution 4:
Many people forget that functions like str_locate_all()
require %>% unlist()
or %>% .[[1]]
.
Then you can easily detect character(0)
with the length()
function if > 0
one can safely use the output of str_locate_all()
for example.
Example:
value <- str_extract_all("kvk :", ascii_digit(8,8)) %>% unlist()
if (length(value) > 0) {
# Do something
}
Solution 5:
My method to solve this problem is dealing with that column only by cast it into a character again and find "character(0)" instead.
For example:
df$interest_column <- as.character(df$interest_column) # Cast it into a character again
df[df$interest_column == "character(0)","interest_column"] <- NA # Assign new value
I hope this is a solution you have asked for.