How to safely drop nothing from a vector when the

2019-08-01 11:50发布

问题:

Suppose I have a vector x = 1:10, and it is constructed by concatenating two other vectors a = integer(0) and b = 1:10 together (this is an edge case). I want to split up the combined vector again into a and b later on. I would have thought I could safely separate them with:

i = seq_along(a)
x[i]
x[-i]

But I discovered that when I use x[-integer(0)] I get integer(0) returned, instead of x itself as I naively thought. What is the best way to do this sort of thing?

回答1:

If you want to use negative indexing and the index may degenerate to integer(0) (for example, the index is computed from which), pad a large "out-of-bound" value to the index. Removing an "out-of-bound" value has no side effect.

x <- 1:10
i <- integer(0)
x[-c(i, 11)]  ## position 11 is "out-of-bound"
# [1]  1  2  3  4  5  6  7  8  9 10

If you bother setting this "out-of-bound" value, here is a canonical choice: 2 ^ 31, because this value has exceeded representation range of 32-bit signed integer, yet it is not Inf.


An alternative way is to do an if test on length(i). For example:

if (length(i)) x[-i] else x

Caution: don't use function ifelse for this purpose.



标签: r vector