Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a sequence starting with 0

Tags:

r

seq

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

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?

like image 322
user1936475 Avatar asked May 21 '26 14:05

user1936475


2 Answers

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.

like image 128
MattBagg Avatar answered May 24 '26 04:05

MattBagg


You mean to do

0:14

or

seq(0, 14)
like image 44
David Robinson Avatar answered May 24 '26 03:05

David Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!