R Basic Syntax

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

Basic Program of Hello World

Once you have setup the environment for R, it is easy to start R command prompt by simply typing the command mentioned below 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 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 system, the command syntax will stay same.

$ Rscript test.R

What are 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 '#' in 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 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 to c and they are frequently 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