R Basic Syntax

In this chapter, you will learn about the basics of R programming, and you will begin this basic with a conventional "Hello World" program. Depending on the requirements, you can either program in the "R" command prompt, or you can simply use an R script file to write your program. So let's start coding and learn the basic syntax.

Basic Program of Hello World

Once you set up the environment for R, it is easy to start the R command prompt by simply typing the following command at your command prompt:

$ R

This command will let you launch the R interpreter with a symbol like this '>', and you start writing the program using command prompt:

> newStr <- "Hello - World!"

> print (newStr)

[1] "Hello - World!"

Now write the same program using R script:

Generally, you will write your programs in script files, and then you implement those scripts at your command prompt using the help of an R interpreter called Rscript. Here is the Hello World Script:

myString <- "Hello, World!"

print ( myString)

Save the code you have written in a file "helo.R" and execute this code at Linux command prompt using the below-mentioned command. Whatever be your OS, either Windows or other systems, the command syntax will stay the same.

$ Rscript test.R

Comments in R Programming

Comments are like helping text within your R source code, and these statements get ignored by the interpreter while running your actual program. The single-line comment is written with the starting symbol '#' at the beginning of the statement as given below:

# My first R program is Hello - World

It can be disadvantageous that R does not support multi-line comment, but you can perform a trick, and its code will look something like this:

if(FALSE) {
"This is an example of how to write multi-line comments.
}

newStr <- "Hello - World!"

print ( newStr)

It is to be noted that the strings while using a Multi-line comment should have to be put inside either Single quote or Double Quote.

Another Example:

The C function in R does something completely different than in C, and they are often used in R programming. Example:

1:4 + 5:8          #look, no loops!

## Output will be: [1] 6 8 10 12 14

c(1, 2, 6, 8, 10) + c(0, 1, 5, 7, 9)

## Output will be: [1] 1 3 11 15 19

The colon operator and the c function are used almost everywhere in R code, so it's good to practice using them.


Scroll Back to Top