safe_ifelse: A safe alternative to ifelse

Description Usage Arguments Details Value Examples

View source: R/safe_ifelse.R

Description

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

Usage

1
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:

Value

Vector of same length and class as yes and no.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 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)

rccmisc documentation built on May 2, 2019, 2:48 p.m.