空字符串

基本类型 / 字符串

# Empty string literal
some_empty_string <- ""
# Built out of nothing
another_empty_string <- character(1)

# nzchar() is TRUE for a non-empty string
is_empty <- !nzchar(some_empty_string)
# is_empty = TRUE
is_another_empty <- !nzchar(another_empty_string)
# is_another_empty = TRUE

# Spaces are not empty
spaces <- "   "
spaces_empty <- !nzchar(spaces)
# spaces_empty = FALSE

# trimws() makes it blank
spaces_blank <- !nzchar(trimws(spaces))
# spaces_blank = TRUE

# character(0) has no strings at all
no_strings <- length(character(0))
# no_strings = 0

cat("is_empty =", is_empty, "\n")
cat("is_another_empty =", is_another_empty, "\n")
cat("spaces_empty =", spaces_empty, "\n")
cat("spaces_blank =", spaces_blank, "\n")
cat("no_strings =", no_strings, "\n")

# if() needs exactly one value
if_error <- tryCatch(if (nzchar(character(0))) 1,
                     error = conditionMessage)
cat("if_error =", if_error, "\n")
# if_error = argument is of length zero