R Tutorial R Charts & Graphs R Statistics R Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

R - Syntax

Although the "Hello World!" program looks simple, it has all the fundamental concepts of R which is necessary to learn to proceed further. Lets start learning R programming by writing a "Hello World!" program. In R, a program can be written at command prompt directly or in a R script file. Lets learn both methods one by one.

R Command Prompt

R allows a user to perform interactive mode programming which involves executing a program by writing directly in the command line. To start interactive programming, call the R interpreter by just typing the following command at the command prompt:

$ R

After this, R interpreter will be launched with a prompt > where a program can be directly written and executed at the command line. In the example below, print "Hello World!" program is written and executed directly at the command line.

> Str <- "Hello World!"
> print(Str)
[1] "Hello World!"

Here, in the first statement a string variable Str is defined, and "Hello World!" is assigned to it using <- operator. After that print() statement is used to print the value of the variable Str.

R Script File

Generally, R programming is done by writing the program in a script file and then executing the script at command prompt with the help of R interpreter called Rscript. The script file can be created by writing the code in the text file and saving the file with the file extension .R. Lets consider a R script called test.R, containing the following code:

#First program in R
Str <- "Hello World!"


The script can be executed at the command prompt using following syntax:

$ Rscript test.R 

This will give the following output:

[1] "Hello World!"

R Comments

The Comments are added in programming code with the purpose of in-code documentation. It makes the code more readable and hence easier to update the code later. It starts with # and ends with the end of that line. Anything after # to the end of the line is a single line comment and will be ignored by the compiler.


The example below shows how to use comments in the R. Comments are ignored by the compiler while running the code.

# first line comment
print('Hello World!') # second line comment

The output of the above code will be:

[1] "Hello World!"