R: A safe alternative to ifelse

safe_ifelse {rccmisc} | R Documentation

## A safe alternative to ifelse

### Description

This function is similair to `ifelse` with differences described in the details section.

### Usage

    safe_ifelse(test, yes, no, na_as_false = TRUE, drop.levels = TRUE)

### Arguments

`test, yes, no` | arguments passed to `ifelse`
`na_as_false` | should `NA` values in `test` be handled as `FALSE`? `TRUE` (which is default) implies that `test & !is.na(test)` must be fullfilled to return values from argument `yes`
`drop.levels` | This only applies when `yes` and `no` are factor variables. The result will then also be a factor. Unused levels (from `yes` and `no` combined) are dropped by default.

### Details

`safe_ifelse` differs from `ifelse` in the following ways:

- Both 'yes' and 'no' must be vectors of the same type or class. This ensures that the output will be of correct format.

- Factors can be combined without problem

- The argument `na.rm` makes it easier to handle cases when `cond = NA`

### Value

Vector of same length and class as `yes` and `no`.

### Examples

    # Test must be TRUE to return 'yes'
    safe_ifelse(NA, 1, 2) ## 2
    ifelse(NA, 1, 2) ## NA

    # Factors are problematic in ifelse
    ifelse(TRUE, as.factor("hello"), 2) ## 1
    ## Not run:
    safe_ifelse(TRUE, as.factor("hello"), 2) ## Error

    ## End(Not run)
    safe_ifelse(TRUE, as.factor("hello"), as.factor(2)) ## hello
    safe_ifelse(TRUE, as.factor("hello"), as.factor(2), drop.levels = FALSE)

[Package rccmisc version 0.3.7 Index]