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

RIf Statement

R Problem Overview


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.....

R Solutions


Solution 1 - R

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 - R

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 - R

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 - R

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 - R

instead of length(), worked for me nrows()

Solution 6 - R

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMethexisView Question on Stackoverflow
Solution 1 - RPatrick RoocksView Answer on Stackoverflow
Solution 2 - RAndrew BrēzaView Answer on Stackoverflow
Solution 3 - RamagardView Answer on Stackoverflow
Solution 4 - REmmanuel ChamilakisView Answer on Stackoverflow
Solution 5 - RBruno GomesView Answer on Stackoverflow
Solution 6 - RJintachart Wyldes ChartpanichView Answer on Stackoverflow