Description Usage Arguments Value Examples
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 vectorized function that returns a logical value, e.g.,
|
The same structure as x
, with those elements meets criteria
replaced with y
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)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.