逻辑运算

基本类型 / 布尔类型

value1 <- TRUE
value2 <- FALSE

value_not1 <- !value1
# value_not1 = FALSE

value_not2 <- !value2
# value_not2 = TRUE

value_and <- value1 && value2
# value_and = FALSE

value_or <- value1 || value2
# value_or = TRUE

value_xor <- xor(value1, value2)
# value_xor = TRUE

# & and | take vectors, && and || one value
both <- c(TRUE, TRUE) & c(TRUE, FALSE)
# both = TRUE FALSE

# The right side is skipped when the left decides
skipped <- FALSE && stop("never evaluated")
# skipped = FALSE

# isTRUE() is TRUE only for a single TRUE
all_true <- isTRUE(c(TRUE, TRUE))
# all_true = FALSE

cat("value_not1 =", value_not1, "\n")
cat("value_not2 =", value_not2, "\n")
cat("value_and =", value_and, "\n")
cat("value_or =", value_or, "\n")
cat("value_xor =", value_xor, "\n")
cat("both =", both, "\n")
cat("skipped =", skipped, "\n")
cat("all_true =", all_true, "\n")

# && needs single values, not vectors
vector_error <- tryCatch(c(TRUE, TRUE) && TRUE,
                         error = conditionMessage)
cat("vector_error =", vector_error, "\n")
# vector_error = 'length = 2' in coercion to
# 'logical(1)'