另一种写法

控制流 / 条件语句 / if/else 语句

latitude <- sample(-90:90, 1)

# if 是表达式:它给出已执行分支的值
location <- if (latitude == 0) {
  "Equator"
} else if (latitude < 0) {
  "Southern Hemisphere"
} else {
  "Northern Hemisphere"
}

# 写在一行
sign <- if (latitude < 0) "-" else "+"

# 陷阱:没有 else 且条件为假时得到 NULL
no_else <- if (latitude > 90) "too far"

cat("latitude =", latitude, "\n")
cat("location =", location, "\n")
cat("sign =", sign, "\n")
cat("is.null(no_else) =", is.null(no_else), "\n")
# is.null(no_else) = TRUE