Reconstructs the TRUE positions from the index vector returned
by which(), producing a logical vector of length n.
Note that this is not a perfect inverse: which() discards
NA and FALSE positions, so the original vector cannot be
fully recovered.
Arguments
- idx
a vector of non-zero whole-number indices. Positive values mark
TRUEpositions; negative values markFALSEpositions (all others becomeTRUE). As in base R, positive and negative indices must not be mixed. Duplicate indices are allowed and result in a singleTRUE(orFALSE) at that position.- n
a single non-negative whole number giving the length of the result. For positive
idx, defaults tomax(idx); for negative or emptyidx, defaults to0L. Must not be less thanmax(abs(idx)).- useNames
logical. If
TRUE(default) andidxhas names, those names are attached to the correspondingTRUEpositions of the result; all other positions receive an empty string. IfFALSEoridxis unnamed, the result has no names. Ignored for negative indices.
Details
Negative indices follow standard R semantics: unwhich(-2, 5)
returns a vector with TRUE everywhere except position 2.
Positive and negative indices must not be mixed.
Note
The positive-index construction (rv[indices] <- TRUE with name
propagation) is based on code by Nick Sabbe; negative-index handling
and input validation are original additions.
References
Sabbe, N. (2012). Inverse of which.
https://stackoverflow.com/questions/7659833/inverse-of-which
Examples
ll <- c(TRUE, FALSE, TRUE, NA, FALSE, FALSE, TRUE)
names(ll) <- letters[seq_along(ll)]
i <- which(ll)
# reconstruct TRUE positions (names preserved on TRUE positions)
unwhich(i, length(ll))
#> a c g
#> TRUE FALSE TRUE FALSE FALSE FALSE TRUE
# without names
unwhich(i, length(ll), useNames = FALSE)
#> [1] TRUE FALSE TRUE FALSE FALSE FALSE TRUE
# negative index: TRUE everywhere except position 2
unwhich(-2, 5)
#> [1] TRUE FALSE TRUE TRUE TRUE
# empty index -> all-FALSE vector
unwhich(integer(0), n = 5L)
#> [1] FALSE FALSE FALSE FALSE FALSE
