简体   繁体   中英

Creating a sequence starting with 0

I like to use the seq() command in R to create a sequence starting at zero. but when I type eg

seq(0:14)

I get the following output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

What am I doing wrong?

As others have said you want 0:14 or seq(from=0,to=14) The reason you get your undesired result is also worth noting.

In this case, the colon operator on its own (as described in ?':' ) is generating the desired regular sequence of integers, which you are then supplying to seq() .

seq() is guessing that you mean seq(along.with = 0:14) which returns a sequence of the same length as the thing you supplied. And of course it is using the default from = 1 . So it gives you a sequence of fifteen integers starting at one. It's roughly analogous to this:

(x <- 0:14)
# [1]  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14

seq(along.with = x, from = 1)
# [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

Despite causing the error you got, this along.with functionality is clearly useful for making sequences that are the same length as some vector/list/matrix:

seq(c(1,"w",5,6,NA))
# [1] 1 2 3 4 5

And we can't say ?seq didn't warn us about naming our arguments:

The interpretation of the unnamed arguments of seq and seq.int is not standard, and it is recommended always to name the arguments when programming.

You mean to do

0:14

or

seq(0, 14)

seq(0, 14)为我提供了以下输入:

[1]  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14

Your problem here is with syntax. i:j creates a sequence from the number i to j; for example 1:5 can be read as 1 to 5 or 1,2,3,4,5.

On the other hand, the function seq takes a 'to' parameter, and a 'from' parameter, both of which must be single numbers. Entering seq(0:14) means that a vector - not a single number - is handed to one of seq's parameters.

What you want is

seq(from=0, to=14) 

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM