Learn R Programming

rccmisc (version 0.3.7)

safe_ifelse: 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.

Value

Vector of same length and class as yes and no.

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

Examples

Run this code
# 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)


Run the code above in your browser using DataLab