R-如何测试 IF 语句中的字符(0)

我想这是难以置信的简单,但我似乎找不到答案。

我正在编写一个 IF 语句,但测试是对象是否返回一个 character(0)值。我不知道如何处理 character(0)的声明。

假设 Test <- character(0)或一个值:

if (identical(Pols4,character(0))) {
print('Empty')
} else {
print('Not Empty')
}

它似乎仍然没有工作... ..。

80200 次浏览

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

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"

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
}

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