Everybody knows that R is an inferior programming language, because vector indices start from 1, whereas in real programming languages like C and Python, array indexing begins from 0.
Sometimes this can be quite annoying if a problem—be it a mathematical
algorithm or a coding challenge—calls for zero-based indexing.
You find yourself having to add
+ 1 to all your indices and it’s easy to
introduce bugs or mix up values with their positions.
Help is at hand. I have worked out how to break R so utterly that it starts counting from zero instead of from one. Someone on Stack Overflow said “just don’t do it!” so naturally I’ve gone ahead and done it.
What’s the first letter of the alphabet? In a normal R session, you get:
x <- letters x #>  "a"
But with my enhanced version, you get the real answer:
x <- index_from_0(letters) x #> "b"
Where’s the “a” then? In the zeroth position, of course:
x #> "a"
It works for replacing elements, and for matrices as well:
m <- index_from_0(matrix(0, 2, 2)) m[0, 1] <- 42 m <- 7 m #> [,1] [,2] #> [1,] 0 42 #> [2,] 7 0
This is made possible with some abuse of S3 objects to redefine the
`[<-` operators such that different methods are used every time you
subset a vector assigned the special class
Want to try it yourself? Download the R package index0 from CRAN:
Or view the source code on GitHub.
I’m sure you’ll agree this will be very useful.