On Indentation in R

A Small Plea 🙏

Coding style, like many other things in life, is highly subjective. What one individual likes can feel like chilli in the eyes for another. Such is life and it's important not to get hung up on these things. That said, I'd like to make a small plea to a subset of the R community: If you use 2 spaces for indentation, please please please trial using 4 or more spaces for your next piece of work. You may prefer it and there's no harm done if not.


Until relatively recently (1 or 2 years at a guess) I followed the tidyverse style guide (or more likely just kept the RStudio default settings) and used 2 spaces for indentation of my code. Whether it was due to my eyes getting poorer or simply spending more time working with other languages, I came to realise that it was hard to quickly parse R code with this little indentation. After trialling 4 spaces, and apologies in advance for the cliché, it was like a fog had lifted! My own code now feels less bunched up and easier to skim through. Similarly, when looking at others' codebases, I find it much easier to grok and orientate myself when they utilise more indentation.

It’s not just me

Whilst a muggle from the UK is unlikely to sway too many opinions, I’m not alone in thinking more spacing is better. The coding standards of the R project itself say:

The R Core Team recommends to use a basic indentation of 4 for R and C (and most likely also Perl) code …

Roger Peng, who advocates for 8 spaces, wrote:

Personally, I’ve found 8 spaces is good for my aging eyes. I think my rule is that the appropriate number of spaces of indentation is proportional to the square of my age (I’m still working on that model though). At this point, code with a 2 space indent is indistinguishable from flush left.

Linus Torvalds, in relation to C, said:

In particular, a two-character indent (which hopefully nobody uses, but people are crazy) will be totally unreadable as a patch if you have the (fairly common, at least in UNIX projects) style of using spaces for less-than-eight-character-indents and tabs for the full 8 characters.

A final thought

Whilst I hope that a few people read this and subsequently change their setup, the reality is that defaults matter and RStudio defaults to 2 spaces for indentation. Unless one of their developers feels inclined to slip in a cheeky change,🙈 🙏, I suspect my eyes will continue to be tested!