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

后端 未结 6 1902
别那么骄傲
别那么骄傲 2020-12-14 14:36

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)

相关标签:
6条回答
  • 2020-12-14 14:54

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

    0 讨论(0)
  • 2020-12-14 14:54

    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
    }
    
    0 讨论(0)
  • 2020-12-14 14:58

    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
    
    0 讨论(0)
  • 2020-12-14 15:04

    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.

    0 讨论(0)
  • 2020-12-14 15:05

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

    0 讨论(0)
  • 2020-12-14 15:08

    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"
    
    0 讨论(0)
提交回复
热议问题