Exercise

Why does this work?

x <- 1:10
if (length(x)) "not empty" else "empty"
#> [1] "not empty"

x <- numeric()
if (length(x)) "not empty" else "empty"
#> [1] "empty"

if returns a value which can be assigned

x1 <- if (TRUE) 1 else 2
x2 <- if (FALSE) 1 else 2

c(x1, x2)
#> [1] 1 2

The book recommends assigning the results of an if statement only when the entire expression fits on one line; otherwise it tends to be hard to read.