从字符串转换

基本类型 / 布尔类型

# R knows "true", "True" and "TRUE"
bool_value1 <- as.logical("true")
# bool_value1 = TRUE

# The word "false" is parsed as FALSE
bool_value2 <- as.logical("false")
# bool_value2 = FALSE

# Other words are not recognised: NA, not FALSE
bool_value3 <- as.logical("yes")
# bool_value3 = NA

# Several words count as true: your own list
str_answer <- "yes"
true_words <- c("true", "yes", "1")
bool_value4 <- tolower(str_answer) %in% true_words
# bool_value4 = TRUE

# "T" and "F" work, and so do whole vectors
bool_values <- as.logical(c("T", "F", "TRUE"))
# bool_values = TRUE FALSE TRUE

cat("bool_value1 =", bool_value1, "\n")
cat("bool_value2 =", bool_value2, "\n")
cat("bool_value3 =", bool_value3, "\n")
cat("bool_value4 =", bool_value4, "\n")
cat("bool_values =", bool_values, "\n")