Conditional Sub-setting and In-place Replacement of Unreal Values
Source:R/subset_if.R
subset_if.RdThe x %[if]% cond operator
selects elements from vector/matrix/array x,
for which the result of cond(x) returns TRUE.
And the x %[!if]% cond operator
selects elements from vector/matrix/array x,
for which the result of cond(x) returns FALSE.
The x %unreal =% repl operator
modifies all unreal (NA, NaN, Inf, -Inf) values of x
with replacement value repl.
Thus, x %unreal =% repl,
is the same as, x[is.na(x) | is.nan(x) | is.infinite(x)] <- repl
Value
For the x %[if]% cond and x %[!if]% cond operators:
The subset_if - operators all return a vector with the selected elements.
For the x %unreal =% repl operator:
The x %unreal =% repl operator does not return any value:
It is an in-place modifier, and thus modifies x directly.
The object x is modified such that all
NA, NaN, Inf, and -Inf elements are replaced with repl.
Examples
x <- c(-10:9, NA, NA)
object_with_very_long_name <- matrix(x, ncol=2)
print(object_with_very_long_name)
#> [,1] [,2]
#> [1,] -10 1
#> [2,] -9 2
#> [3,] -8 3
#> [4,] -7 4
#> [5,] -6 5
#> [6,] -5 6
#> [7,] -4 7
#> [8,] -3 8
#> [9,] -2 9
#> [10,] -1 NA
#> [11,] 0 NA
object_with_very_long_name %[if]% \(x)x %in% 1:10
#> [1] 1 2 3 4 5 6 7 8 9
object_with_very_long_name %[!if]% \(x)x %in% 1:10
#> [1] -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 NA NA
x <- c(1:9, NA, NaN, Inf)
print(x)
#> [1] 1 2 3 4 5 6 7 8 9 NA NaN Inf
x %unreal =% 0 # same as x[is.na(x)|is.nan(x)|is.infinite(x)] <- 0
print(x)
#> [1] 1 2 3 4 5 6 7 8 9 0 0 0