How to add comments in R

Overview

​​We can introduce comments to a code to make it more understandable and readable.

In the R programming language, we can add comments in two ways:

  • Before a line of code
  • After a line of code

Commenting before a line of code

Let’s comment before a line of code.

Code

# Comment before a code
'Hello World'

Commenting after a line of code

Now, let’s comment after a line of code.

Code

'Hello World'# Comment before a code

We can see that the comment after a code in R does not affect the code.

Commenting to prevent code execution

In addition to explaining a code, we can use comments to prevent a code from executing. We use the # symbol right before the code to prevent it from executing.

Code

# 'Hello World, hope you are fine?'
'Hello World, good morning!'

Multiline comments

The R language is unique because it has no syntax for multiline comments. However, we can add # right before we comment to continue a comment in the following line.

Code

# This is the first comment
# this is the second comment
# this is the third comment
'Hello World'

Free Resources