当负索引可能是整数(0)时,如何安全地从向量中删除任何内容? [英] How to safely drop nothing from a vector when the negative index could be integer(0)?
问题描述
假设我有一个向量 x = 1:10
,它是通过连接另外两个向量 a = integer(0)
和 b = 1 来构造的:10
在一起(这是一个边缘情况).我想稍后再次将组合向量拆分为 a
和 b
.我原以为我可以安全地将它们分开:
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]
但我发现当我使用 x[-integer(0)]
我得到 integer(0)
返回,而不是 x
正如我天真地认为的那样.做这种事情的最佳方法是什么?
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?
推荐答案
如果你想使用负索引并且索引可能退化为 integer(0)
(例如,索引是从which
),将一个大的越界"值填充到索引中.删除越界"值没有副作用.
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
如果你麻烦设置这个out-of-bound"值,这里有一个规范的选择:2 ^ 31
,因为这个值已经超出了 32 位有符号整数的表示范围,但是它不是 Inf
.
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
.
另一种方法是对 length(i)
进行 if
测试.例如:
An alternative way is to do an if
test on length(i)
. For example:
if (length(i)) x[-i] else x
注意:不要将函数 ifelse
用于此目的.
Caution: don't use function ifelse
for this purpose.
这篇关于当负索引可能是整数(0)时,如何安全地从向量中删除任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!