问题描述
在 lower == upper - 1
的极端情况下,R 的 seq
函数的聪明才智"不止一次地打击了我:
More than once the "cleverness" of R's seq
function has hit me badly in the corner case when lower == upper - 1
:
> 1:0
[1] 1 0
> seq(1, 0)
[1] 1 0
> seq(1, 0, 1)
Error in seq.default(1, 0, 1) : wrong sign in 'by' argument
我不是在问这种奇怪行为的原因——我认为它现在只是我们必须忍受的遗产.相反,我想知道是否有任何包实现了在这种情况下返回空序列的 seq
运算符,如下所示:
I'm not asking for the reasons of this odd behavior -- I assume it's now just a legacy that we have to live with. Instead, I'd like to know if any package implements a seq
operator that returns an empty sequence in this case, like the following:
safe.seq.int <- function(from, to, by=1) {
if (from > to) integer(0) else seq.int(from, to, by)
}
> safe.seq.int(1, 0)
integer(0)
推荐答案
正是出于这个原因,最好使用 seq_len(n)
而不是 1:n
-如果 n=0
那么你会得到一个空序列而不是 c(1,0)
.
It's good practice to use seq_len(n)
instead of 1:n
for exactly this reason - if n=0
then you get an empty sequence rather than c(1,0)
.
希望能帮到你
这篇关于如果下限大于上限,则创建一个空序列的序列构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!