Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 133

4.5.1.3 The Switch-statement

Оглавление

An if-else construct that assigns one value to a variable based on one other variable can be condensed via the switch() function.

switch()

x <- ‘b’ x_info <- switch(x, ‘a’ = “One”, ‘b’ = “Two”, ‘c’ = “Three”, stop(“Error: invalid `x` value”) ) # x_info should be ‘two’ now: x_info ## [1] “Two”

The switch statement can always be written a an else-if statement. The following code does the same as the aforementioned code.

x <- ‘b’ x_info <- if (x == ‘a’ ) { “One” } else if (x == ‘b’) { “Two” } else if (x == ‘c’) { “Three” } else { stop(“Error: invalid `x` value”) } # x_info should be ‘two’ now: x_info ## [1] “Two”

The switch() statement can always be written as with the if-else-if construction, which in its turn can always be written based on with if-else statements. This is same logic also applies for loops (that repeat parts of code). All loop constructs can always be written with a for-loop and an if-statement, but more advanced structures help to keep code clean and readable.

The Big R-Book

Подняться наверх