iif: Quick vectorized call of 'ifelse'

Description Usage Arguments Value Examples

Description

ifelse(is.null(x), y, x) is less handy in some situations. You can use ifnull(x, y) instead. It is a vectorized implementation of ifelse equivalents. Moreover, it supports recursive conversion for lists. It is inspired by Nz function in VBA.

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
iif(x, y, criteria = is.null)

ifnull(x, y)

ifna(x, y)

ifnan(x, y)

ifblank(x, y)

ifempty(x, y)

ifzero(x, y)

Arguments

x

Vector, matrix, data.frame, array or list. The elements of x that do not meet the criteria function (e.g., is.null, is.na, ...), will be returned as-is. The elements of x that meet the criteria function, will be converted to y.

y

Scalar, if a vector is given, only the first element will be used. The elements of x that meet the criteria function, will be converted to y.

criteria

A vectorized function that returns a logical value, e.g., is.null, is.na. You can also compose a function on your own.

Value

The same structure as x, with those elements meets criteria replaced with y

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
## Not run: 
ifna(c(1, 4, NA), 0)  # returns
# [1] 1  4  0

# iif also supports recursive conversion
ifnull(list(3, list(NULL), c(3, 5)), 0)  # returns
# [[1]]
# [1] 3
# 
# [[2]]
# [[2]][[1]]
# [1] 0
# 
# [[3]]
# [1] 3 5

ifzero(data.frame(A=c(1, 0, -2), B=c(-1, 0, 3)), 99)  # returns
#    A   B
# 1  1  -1
# 2 99  99
# 3 -2   3

# User-defined function 
iif(matrix(c(1, 0, -2, -1, 0, 3), nrow=2), 0, function(v) v < 0)
## Replace all the negative values with 0
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    0    3

# Also works for high-dimensional array
iif(array(1:6, dim=c(1, 3, 2)), NA, function(v) v %% 2 == 0)
## Replace all the even numbers with NA
# ,, 1
#      [,1]  [,2]  [,3]
# [1,]    1    NA     3
#
# , , 2
#      [,1]  [,2]  [,3]
# [1,]   NA     5    NA

## End(Not run)

madlogos/aseshms documentation built on May 21, 2019, 11:03 a.m.