Hello World

The first step to learning any language is the classic "Hello World" program.

The Classic Hello World Program

The first program we are going to write is the classic Hello World program.

The purpose of this program is to display the text “Hello World!” to the user. Let’s begin.

Press + to interact
# Simply use the print() keyword
# Write anyting between quotation marks to print on console.
print("Hello World")

A name/text followed by brackets () is called a function. We will be learning functions in a later chapter. But for now, just remember that functions are used to perform a task. For example, this print() function is performing a task, i.e., printing.

Comments in R

You might also notice other peculiar lines in the above code (Line number 1 and 2). These lines are comments and they begin with the character #. For example:

# This is a comment

Comments are not executed by the compiler. They are ignored while executing a program. However, it is important to give comments so that the code becomes readable. Also, it helps other programmers to know exactly what is going on in the code.

The code below contains only comments:

Press + to interact
# This is a comment.
# This is another comment.
# Comments are not executed.

If we don’t want the quotes displayed around the text “Hello World”, we can use the argument quote. If it is set to TRUE then " " quotation marks will be printed on the console, but if it is set to FALSE quotation marks will be suppressed.

Arguments are extra instructions that you can provide. We will learn more about it in the Functions chapter.

print("Hello World", quote = TRUE)
Testing the output of print() when quote parameter is set to TRUE

However, there is a twist. There is another method for printing in R; cat(). This also takes the data to print the same way print() does.

Press + to interact
# Another method to print Hello World
cat("Hello World")

Notice, that the quotation marks are already suppressed! If we want to print the quotation marks, we will have to do so explicitly. For example:

Press + to interact
# Printing quotation marks using cat() keyword
cat("\"Hello World\"")

Here \" is an escape sequence. We will be learning about them in a later chapter.

There is another method for displaying text on the screen. However, this method is not preferred. The R language is console based, so we can type any data directly into R’s program and it will be displayed.

This method is not very useful for any kind of serious work, data manipulation, etc.

For example: in this code, we simply write “Hello World” and the compiler displays it on screen.

Press + to interact
"Hello World"