Comments are portions of a computer program that are used to describe a piece of code. For example,
# declare variable
age = 24
# print variable
print(age)
Here, # declare variable
and # print variable
are two comments used in the code.
Comments have nothing to do with code logic. They do not get interpreted or compiled and are completely ignored during the execution of the program.
In general, all programming languages have the following types of comments:
However, in R programming, there is no functionality for multi-line comments. Thus, you can only write single-line comments in R.
You use the #
symbol to create single-line comments in R. For example,
# this code prints Hello World
print("Hello World")
Output
[1] "Hello World"
In the above example, we have printed the text Hello World
to the screen. Here, just before the print statement, we have included a single-line comment using the #
symbol.
Note: You can also include a single-line comment in the same line after the code. For example,
print("Hello World") # this code prints Hello World
As already mentioned, R does not have any syntax to create multi-line comments.
However, you can use consecutive single-line comments to create a multi-line comment in R. For example,
# this is a print statement
# it prints Hello World
print("Hello World")
Output
[1] "Hello World"
In the above code, we have used multiple consecutive single-line comments to create a multi-line comment just before the print statement.
As discussed above, R comments are used to just document pieces of code. This can help others to understand the working of our code.
Here are a few purposes of commenting on an R code:
As an R developer, your task is not only to write effective code. At times, you may also need to read codes written by other developers and modify them. In such a case, a well-written comment might be a lifesaver.
You should always keep in mind the following points while writing comments.