空字符串

基本类型 / 字符串

# 空字符串字面量
some_empty_string <- ""
# 凭空构造
another_empty_string <- character(1)

# 对非空字符串,nzchar() 为 TRUE
is_empty <- !nzchar(some_empty_string)
# is_empty = TRUE
is_another_empty <- !nzchar(another_empty_string)
# is_another_empty = TRUE

# 空格不算空
spaces <- "   "
spaces_empty <- !nzchar(spaces)
# spaces_empty = FALSE

# trimws() 处理后变为空字符串
spaces_blank <- !nzchar(trimws(spaces))
# spaces_blank = TRUE

# character(0) 里一个字符串也没有
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() 恰好需要一个值
if_error <- tryCatch(if (nzchar(character(0))) 1,
                     error = conditionMessage)
cat("if_error =", if_error, "\n")
# if_error = argument is of length zero