Site icon R-bloggers

R Comments

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.


Types of Comments in R

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.


1. R Single-Line Comments

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 

2. R Multi-Line Comments

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.


Purpose of Comments

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:


How to Create Better Comments?

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.

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.