为什么 seq(0:3) = 1 2 3 4?

Hos*_*eon 4 r

我正在学习 R,并且我在 seq() 上遇到问题\n我知道 seq(0, 3) 是 0 1 2 3。\n但我不知道为什么 seq(0:3) 是1 2 3 4。

\n

在 RDocumentation(https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/seq)中,它说

\n
seq(from, to)\nseq(from, to, by= )\nseq(from, to, length.out= )\nseq(along.with= )\nseq(from)\nseq(length.out= )\n
Run Code Online (Sandbox Code Playgroud)\n

第一种形式生成序列 from, from+/-1, \xe2\x80\xa6, to (与 from:to 相同)。

\n

那么 seq(0, 3) 和 seq(0:3) 是不是相同?

\n

MrF*_*ick 6

不。seq(0,3)seq(0:3)不相同。from=在第一种情况下,您使用参数 (和)调用函数to=,而在第二种情况下,您将单个参数传递给函数 ( from=)。传递单个值或向量并不重要(因为 R 中没有单个值,只有长度为 1 的向量)。考虑

seq(3:6)
[1] 1 2 3 4
Run Code Online (Sandbox Code Playgroud)

如果只传递一个参数seq()并且其长度大于 1,则它将返回序列 1 到对象的长度。稍后在帮助文件中描述了此行为

第五种形式生成序列 1, 2, ..., length(from) (就好像已经指定了参数 around.with 一样),除非参数在解释为 1:from 时是长度为 1 的数字(即使对于 seq (0) 与 S) 兼容。首选使用 seq_along 或 seq_len(除非严格的 S 兼容性是必需的)。

其中“第一种形式... [is](与 from:to 相同)”的部分表示与seq(0, 3)相同0:3,而不是seq(0:3)

您可以在 的代码中看到此行为seq.default。对单个参数的检查发生在代码的早期

...
if ((One <- nargs() == 1L) && !missing(from)) {
    lf <- length(from)
    return(if (mode(from) == "numeric" && lf == 1L) {
        if (!is.finite(from)) stop("'from' must be a finite number")
        1L:from
    } else if (lf) 1L:lf else integer())
}
...
Run Code Online (Sandbox Code Playgroud)