Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is seq(0:3) = 1 2 3 4?

I’m learning R, and I’ve got problem at seq()
I know that seq(0, 3) is 0 1 2 3.
But I don’t know why seq(0:3) is 1 2 3 4.

In RDocumentation(https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/seq), it says that

seq(from, to)
seq(from, to, by= )
seq(from, to, length.out= )
seq(along.with= )
seq(from)
seq(length.out= )

The first form generates the sequence from, from+/-1, …, to (identical to from:to).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So isn’t it true that seq(0, 3) and seq(0:3) are identical?

>Solution :

No. seq(0,3) and seq(0:3) are not identical. In the first case you are calling the function with the parameters (from= and to=) and in the second cause you are passing a single parameter to the function (from=). It doesn’t matter if you pass a single value or a vector (because there are no single values in R, just vectors of length 1). Consider

seq(3:6)
[1] 1 2 3 4

If you pass just one argument to seq() and it has a length greater than 1, it will return the sequence 1 to the length of the object. This behavior is described later in the help file

The fifth form generates the sequence 1, 2, …, length(from) (as if argument along.with had been specified), unless the argument is numeric of length 1 when it is interpreted as 1:from (even for seq(0) for compatibility with S). Using either seq_along or seq_len is much preferred (unless strict S compatibility is essential).

The part where it says "The first form … [is] (identical to from:to)" means that seq(0, 3) is the same as 0:3, not seq(0:3)

You can see this behavior in the code for seq.default. The check for a single argument happens early in the code

...
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())
}
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading