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

4.5.1.2 The Vectorised If-statement

Оглавление

The function ifelse() is the vectorised version of the if-function. It allows to use vectors as input and output. While the if-statement is useful for controlling flow in code, the ifelse-function handy for data manipulation.

ifelse()

x <- 1:6 ifelse(x %% 2 == 0, ‘even’, ‘odd’) ## [1] “odd” “even” “odd” “even” “odd” “even”

The ifelse function can also use vectors as parameters in the output.

x <- 1:6 y <- LETTERS[1:3] ifelse(x %% 2 == 0, ‘even’, y) ## [1] “A” “even” “C” “even” “B” “even” # Note that y gets recycled!

The Big R-Book

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