Leading vs trailing commas on new lines


#1

There are circumstances when it makes sense to place elements on new lines: function calls with a lot of arguments, manual composition of data using c() or tribble() etc.

Question: am I the only person who uses leading commas on new lines? In other words, am I the only person who does this ...

c('element a'
   , 'element b'
   , 'element c')

instead of this ...

c('element a',
   'element b',
   'element c')

I've been using leading commas for years and didn't think anything of it until someone noticed it and commented on it. It suddenly struck me that I never see this in code examples anywhere. I like my method because it's a very clear signal that a line is meant to continue a preceding line. The position of the comma is variable on the right, but fixed on the left.

Does this make me a leftist?


#2

Interesting. I've never done (or thought to do) this with R code but I tend to do this with SQL pretty often. It makes it easier to remove lines from a query without having to change two lines.

For example:

SELECT
column1
,column2
,column3
FROM table

If I delete ,column2 I can remove that line without having to remove anything from the other lines.


#3

It works, but I can see 2 disadvantages:

  • auto-formatting packages will not align your code properly because they are written with the expectation that the comma would be at the end of the line

  • writing the comma at the end of the line creates consistency with other code for which you need to have the "connecting element" at the end of the line to tell R that your code is not over (e.g. ggplot in which you need to keep the + at the end of the line)


#4

I definitely trail with commas, but your reasoning makes sense. I guess the other thing is that, with R, a leading comma makes me think of bracket notation [,1].


#5

Like @kentm, I do this in my SQL code, and I would use this style with R code if it the RStudio formatter (or the {lintr} or {styler} packages) supported it. I'm not sure how difficult it would be to implement, but I would certainly appreciate it if it were supported. (Perhaps it could be an option in RStudio's Global Options > Code menu.)