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)
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()
.
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
}
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
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.
instead of length()
, worked for me nrows()
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"