Indexing from zero in R

[This article was first published on R on Tea & Stats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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[1]

#> [1] "a"

But with my enhanced version, you get the real answer:

x <- index_from_0(letters)
x[1]

#> "b"

Where’s the “a” then? In the zeroth position, of course:

x[0]

#> "a"

It works for replacing elements, and for matrices as well:

m <- index_from_0(matrix(0, 2, 2))
m[0, 1] <- 42
m[1] <- 7
m

#>      [,1] [,2]
#> [1,]    0   42
#> [2,]    7    0

This is made possible with some abuse of S3 objects to redefine the `[` and `[<-` operators such that different methods are used every time you subset a vector assigned the special class index0.

Want to try it yourself? Download the R package index0 from CRAN:

install.packages('index0')

Or view the source code on GitHub.

I’m sure you’ll agree this will be very useful.

To leave a comment for the author, please follow the link and comment on their blog: R on Tea & Stats.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)