Comments - where to

Author
Published

January 10, 2024

1 Where to add comments in R code and Quarto MarkDown

Exercise #1

What do you think about the way these comments have been placed? Will it work?

# this comment definitely okay
x <- 2 + 2

# ...but is the following okay?
tibble(x=1:10, y=2:11) %>% # ..is it okay, mid-pipe?
  filter(y>5 & # and how about breaking in the middle..
  x != 9) # ..of a statement like 'filter'?

This is what the output looks like:

# A tibble: 5 × 2
      x     y
  <int> <int>
1     5     6
2     6     7
3     7     8
4     8     9
5    10    11

…so the code seems to run without fault - R is actually quite tolerant about placing comments here, there and everywhere, but is it good practice, though?

These comments are syntactically okay … but did they make your code simpler for humans to read? No not really. In fact, they made it rather more difficult than it needed to be. So click below to keep it simple:

# Comment lines before the code
# can be multiple lines and does
# not disturb your reading of the
# code ... best practice!

x <- 2 + 2 # use inline comments sparringly
y <- x^2 - c(2, 5, 8, 10:14) # ..they are distracting!