Description Usage Arguments Details Value See Also Examples
ifelse(is.null(x), y, x)
is less handy in some situations. You can use
iif(x, y, criteria)
instead. Inspired by Nz
function in VBA,
it is a vectorized implementation of ifelse
equivalents. Moreover,
it supports recursive conversion (especially useful for lists).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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 |
y |
Scalar, if a vector is given, only the first element will be used.
The elements of x that meet the |
criteria |
A function (prefer a vectorized one) that returns a logical value, e.g.,
|
The philosophy of iif
is to replace elements in x
that
matches criteria
(must be a vectorized function returning logical outputs)
with scalar value y
. For instance, iif(x, y, is.null)
will convert
all the NULL values in x with y. The short-hand call is ifnull(x, y)
.
The iif
function family contains some quick calls:
ifzero(x, y)
replace elements in x with y where x==0
ifna(x, y)
or ifnan(x, y)
replace elements in x with y where x is NA or NaN
ifnull(x, y)
replace elements in x with y where x is NULL
ifblank(x, y)
replace elements in x with y where nchar(x)==0
ifempty(x, y)
replace elements in x with y where length(x)==0
ifspace(x, y)
replace elements in x with y where x is white spaces
ifpositive(x, y)
replace elements in x with y where x>0
ifnegative(x, y)
replace elements in x with y where x<0
The same structure as x
, with those elements which meet criteria
replaced with y
. Those elements which do not meet criteria
will
be left as-is.
If you have two options for replacement, you may need the vectorized
implementation of ifelse
: if_else()
.
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:8, dim=c(1, 4, 2)), NA, function(v) v %% 2 == 0)
## Replace all the even numbers with NA
# ,, 1
# [,1] [,2] [,3] [,4]
# [1,] 1 NA 3 NA
#
# , , 2
# [,1] [,2] [,3] [,4]
# [1,] 5 NA 7 NA
## End(Not run)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.