4.3 A brief style guide: Commenting and spacing
Like all programming languages, R isn’t just meant to be read by a computer, it’s also meant to be read by other humans – or very well-trained dolphins. For this reason, it’s important that your code looks nice and is understandable to other people and your future self. To keep things brief, I won’t provide a complete style guide – instead I’ll focus on the two most critical aspects of good style: commenting and spacing.
Howwouldyouliketoreadabookiftherewerenospacesbetweenwords? I’mguessingyouwouldn’t. Soeverytimeyouwritecodewithoutproperspacing,rememberthissentence.
Commenting isn’t the only way to make your code legible. It’s important to make appropriate use of spaces and line breaks. For example, I include spaces between arithmetic operators (like =, + and -) and after commas (which we’ll get to later). For example, look at the following code:
# Shitty looking code a<-(100+3)-2 mean(c(a/100,642564624.34)) t.test(formula=revenue.all~sequel,data=movies) plot(x=movies$budget,y=movies$dvd.usa,main="myplot")
That code looks like shit. Don’t write code like that. It makes my eyes hurt. Now, let’s use some liberal amounts of commenting and spacing to make it look less shitty.
# Some meaningless calculations. Not important a <- (100 + 3) - 2 mean(c(a / 100, 642564624.34)) # t.test comparing revenue of sequels v non-sequels t.test(formula = revenue.all ~ sequel, data = movies) # A scatterplot of budget and dvd revenue. # Hard to see a relationship plot(x = movies$budget, y = movies$dvd.usa, main = "myplot")
See how much better that second chunk of code looks? Not only do the comments tell us the purpose behind the code, but there are spaces and line-breaks separating distinct elements.
There are a lot more aspects of good code formatting. For a list of recommendations on how to make your code easier to follow, check out Google’s own company R Style guide at https://google-styleguide.googlecode.com/svn/trunk/Rguide.xml