ID EN
Control Flow

ifelse

R Base 3.6.2 🇮🇩 Bahasa Indonesia

ifelse mengembalikan nilai dengan bentuk yang sama seperti tes yang diisi dengan elemen yang dipilih dari ya atau tidak tergantung pada apakah elemen tes tersebut TRUE atau FALSE.

Syntax

R
ifelse(test, yes, no)

Arguments

Parameter Deskripsi
test an object which can be coerced to logical mode.
yes return values for true elements of test.
no return values for false elements of test.

Return Value

Vektor dengan panjang dan atribut yang sama (termasuk dimensi dan "kelas") sebagai nilai pengujian dan data dari nilai ya atau tidak. Modus jawabannya akan dipaksa dari logika untuk mengakomodasi terlebih dahulu nilai apa pun yang diambil dari ya dan kemudian nilai apa pun yang diambil dari tidak.

Details

Jika ya atau tidak terlalu pendek, elemennya akan didaur ulang. ya akan dievaluasi jika dan hanya jika ada elemen tes yang benar, dan analog dengan tidak. Nilai yang hilang dalam tes memberikan nilai yang hilang pada hasilnya.

Contoh

Example
R
# NOT RUN {
x <- c(6:-4)
sqrt(x)  #- gives warning
sqrt(ifelse(x >= 0, x, NA))  # no warning

## Note: the following also gives the warning !
ifelse(x >= 0, sqrt(x), NA)


## ifelse() strips attributes
## This is important when working with Dates and factors
x <- seq(as.Date("2000-02-29"), as.Date("2004-10-04"), by = "1 month")
## has many "yyyy-mm-29", but a few "yyyy-03-01" in the non-leap years
y <- ifelse(as.POSIXlt(x)$mday == 29, x, NA)
head(y) # not what you expected ... ==> need restore the class attribute:
class(y) <- class(x)
y
## This is a (not atypical) case where it is better *not* to use ifelse(),
## but rather the more efficient and still clear:
y2 <- x
y2[as.POSIXlt(x)$mday != 29] <- NA
## which gives the same as ifelse()+class() hack:
stopifnot(identical(y2, y))


## example of different return modes (and 'test' alone determining length):
yes <- 1:3
no  <- pi^(1:4)
utils::str( ifelse(NA,    yes, no) ) # logical, length 1
utils::str( ifelse(TRUE,  yes, no) ) # integer, length 1
utils::str( ifelse(FALSE, yes, no) ) # double,  length 1
# }

See Also

if.