Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 131
Hint – Extending the if-statement
ОглавлениеIt is possible to have more than one else-if statement and/or use nested statements.
x <- 122 if (x < 10) { print(‘less than ten’) } else if (x < 100) { print(‘between 10 and 100’) } else if (x < 1000) { print(‘between 100 and 1000’) } else { print(‘bigger than 1000 (or equal to 1000)’) } ## [1] “between 10 and 1000”
Note that the statements do not necessarily have to be encapsulated by curly brackets if the statement only takes one line.
x <- TRUE y <- pi y <- if (x) 1 else 2 y # y is now 1 ## [1] 1
Note that hybrid forms are possible, but it gets confusing very fast. In the following piece of code the variable y
will not get the value one, but rather six.
z <- y <- if (x) {1; z <- 6} else 2 y # y is now 6 ## [1] 6 z # z is also 6 ## [1] 6