[R] x[0]: Can '0' be made an allowed index in R?

@vi@e@gross m@iii@g oii gm@ii@com @vi@e@gross m@iii@g oii gm@ii@com
Mon Apr 22 03:05:39 CEST 2024


Hans,

It is a good question albeit R made a conscious decision to have indices
that correspond to things like row numbers and thus start with 1. Some
others have used a start of zero but often for reasons more related to
making use of all combinations of the implementation of integers on many
machines where starting with 1 would only allow use of the 255 of the 256
combinations available in 8 bits and so on.

My solution when I needed to start with zero is simply to do things like
x[n+1] or have a small function that does an increment like x[inc(n)] that
makes very clear what is happening.

You have been given several possible ways closer to what you want and that
may work for you but may confuse anyone else ever looking at your code so I
would add some comments or documentation explaining your non-standard use.

But do note the possibility of issues with any solution if you use other
indexing methods like x[5:8] which might not be done consistently. 

And if you were using a 2-D structure like a matrix or data.frame, would
your columns also be starting with column 0 as in mydata[0,0] to get the
first item in the first row, or are columns still 1-based while rows are
not?

Beware some solutions may be incomplete and may result in subtle errors.
Just routinely adding 1 seems safer as you know what you will get.


-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Hans W
Sent: Sunday, April 21, 2024 3:56 AM
To: R help project <r-help using r-project.org>
Subject: [R] x[0]: Can '0' be made an allowed index in R?

As we all know, in R indices for vectors start with 1, i.e, x[0] is not a
correct expression. Some algorithms, e.g. in graph theory or combinatorics,
are much easier to formulate and code if 0 is an allowed index pointing to
the first element of the vector.

Some programming languages, for instance Julia (where the index for normal
vectors also starts with 1), provide libraries/packages that allow the user
to define an index range for its vectors, say 0:9 or 10:20 or even negative
indices.

Of course, this notation would only be feasible for certain specially
defined vectors. Is there a library that provides this functionality?
Or is there a simple trick to do this in R? The expression 'x[0]' must
be possible, does this mean the syntax of R has to be twisted somehow?

Thanks, Hans W.

	[[alternative HTML version deleted]]

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list