Basic Syntax in R Programming
R is the most popular language used for Statistical Computing and Data Analysis with the support of over 10, 000+ free packages in CRAN repository.
Like any other programming language, R has a specific syntax which is important to understand if you want to make use of its powerful features.
This article assumes R is already installed on your machine. We will be using RStudio but we can also use R command prompt by typing the following command in the command line.
This will launch the interpreter and now let’s write a basic Hello World program to get started.
We can see that “Hello, World!” is being printed on the console.
Now we can do the same thing using
print() which prints to the console. Usually, we will write our code inside scripts which are called RScripts in R. To create one, write the below given code in a file and save it as myFile.R and then run it in console by writing:
 "Hello, World!"
Syntax of R program
A program in R is made up of three things: Variables, Comments, and Keywords. Variables are used to store the data, Comments are used to improve code readability, and Keywords are reserved words that hold a specific meaning to the compiler.
Variables in R
Previously, we wrote all our code in a print() but we don’t have a way to address them as to perform further operations. This problem can be solved by using variables which like any other programming language are the name given to reserved memory locations that can store any type of data.
In R, the assignment can be denoted in three ways:
- = (Simple Assignment)
- <- (Leftward Assignment)
- -> (Rightward Assignment)
"Simple Assignment" "Leftward Assignment!" "Rightward Assignment"
Comments in R
Comments are a way to improve your code’s readability and are only meant for the user so the interpreter ignores it. Only single-line comments are available in R but we can also use multiline comments by using a simple trick which is shown below. Single line comments can be written by using # at the beginning of the statement.
 "This is fun!"
From the above output, we can see that both comments were ignored by the interpreter.
Keywords in R
Keywords are the words reserved by a program because they have a special meaning thus a keyword can’t be used as a variable name, function name, etc.
We can view these keywords by using either
- if, else, repeat, while, function, for, in, next and break are used for control-flow statements and declaring user-defined functions.
- The ones left are used as constants like
TRUE/FALSEare used as boolean constants.
NaNdefines Not a Number value and
NULLare used to define an Undefined value.
Infis used for Infinity values.
Note: R is a case sensitive language so
TRUEis not same as True.My Personal Notes arrow_drop_up