basic-syntax-in-r-programming
basic-syntax-in-r-programming
Output:
[1] "Hello, World!"
Syntax of R program
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:
1. = (Simple Assignment)
2. <- (Leftward Assignment)
3. -> (Rightward Assignment)
Example:
Output:
"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.
Example:
Output:
[1] "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 help(reserved) or ?reserved.
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/FALSE are used as boolean
constants.
NaN defines Not a Number value and NULL are used to define an Undefined
value.
Inf is used for Infinity values.
Note: R is a case sensitive language so TRUE is not same as True.
Comments in R
s
Comments are generic English sentences, mostly written in a program to explain what it does
or what a piece of code is supposed to do. More specifically, information that programmer
should be concerned with and it has nothing to do with the logic of the code. They are
completely ignored by the compiler and are thus never reflected on to the input.
The question arises here that how will the compiler know whether the given statement is a
comment or not?
The answer is pretty simple. All languages use a symbol to denote a comment and this symbol
when encountered by the compiler helps it to differentiate between a comment and statement.
Comments are generally used for the following purposes:
Code Readability
Explanation of the code or Metadata of the project
Prevent execution of code
To include resources
Types of Comments
There are generally three types of comments supported by languages, namely-
Single-line Comments- Comment that only needs one line
Multi-line Comments- Comment that requires more than one line.
Documentation Comments- Comments that are drafted usually for a quick
documentation look-up
Note: R doesn’t support Multi-line and Documentation comments. It only supports single-line
comments drafted by a ‘#’ symbol.
Comments in R
As stated in the Note provided above, currently R doesn’t have support for Multi-line comments
and documentation comments. R provides its users with single-lined comments in order to add
information about the code.
Single-Line Comments in R
Single-line comments are comments that require only one line. They are usually drafted to
explain what a single line of code does or what it is supposed to produce so that it can help
# vaagdevi
The above code when executed will not produce any output, because R will consider the
statement as a comment and hence the compiler will ignore the line.
Example 2:
a <- 9
b <- 4
# Printing sum
print(a + b)
Output:
[1] 13
Commenting Multiple Lines
As stated earlier that R doesn’t support multi-lined comments, but to make the commenting
process easier, R allows commenting multiple single lines at once. There are two ways to add
multiple single-line comments in R Studio:
First way: Select the multiple lines which you want to comment using the cursor and
then use the key combination “control + shift + C” to comment or uncomment the selected
lines.
Second way: The other way is to use the GUI, select the lines which you want to
comment by using the cursor and click on “Code” in menu, a pop-up window pops out in
which we need to select “Comment/Uncomment Lines” which appropriately comments or
uncomment the lines which you have selected.
This makes the process of commenting a block of code easier and faster than adding # before
each line one at a time.
R – Operators
Operators are the symbols directing the compiler to perform various kinds of
operations between the operands. Operators simulate the various mathematical,
logical, and decision operations performed on a set of Complex Numbers, Integers,
and Numericals as input operands.
R Operators
R supports majorly four kinds of binary operators between a set of operands
Types of the operator in R language
Arithmetic Operators
Logical Operators
Relational Operators
Assignment Operators
Miscellaneous Operator
Arithmetic Operators
Arithmetic operations simulate various math operations, like addition, subtraction,
multiplication, division, and modulo using the specified operator between operands,
which may be either scalar values, complex numbers, or vectors. The operations are
performed element-wise at the corresponding positions of the vectors.
Addition operator (+):
The values at the corresponding positions of both the operands are added. Consider
the following R snippet to add two vectors:
Input : a <- c (1, 0.1)
b <- c (2.33, 4)
print (a+b)
Output : 3.33 4.10
Subtraction Operator (-):
The second operand values are subtracted from the first. Consider the following R
snippet to subtract two variables:
Input : a <- 6
b <- 8.4
print (a-b)
Output : -2.4
Multiplication Operator (*):
The multiplication of corresponding elements of vectors and Integers are multiplied
with the use of the ‘*’ operator.
Input : B= matrix(c(4,6i),nrow=1,ncol=2)
C= matrix(c(2,2i ),nrow=1, ncol=2)
print (B*C)
Output : 8+0i -12+0i
The elements at corresponding positions of matrices are multiplied.
Division Operator (/):
The first operand is divided by the second operand with the use of the ‘/’ operator.
Input : a <- 1
b <- 0
print (a/b)
Output : -Inf
Power Operator (^):
R
# R program to illustrate
Output:
Addition of vectors : 2 5
Subtraction of vectors : -2 -1
Multiplication of vectors : 0 6
Division of vectors : 0 0.6666667
Modulo of vectors : 0 2
Power operator : 0 8
Logical Operators
Logical operations simulate element-wise decision operations, based on the specified
operator between the operands, which are then evaluated to either a True or False
boolean value. Any non-zero integer value is considered as a TRUE value, be it a
complex or real number.
Element-wise Logical AND operator (&):
Returns True if both the operands are True.
Input : list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1 & list2)
Output : FALSE TRUE
Any non zero integer value is considered as a TRUE value, be it
complex or real number.
Element-wise Logical OR operator (|):
Returns True if either of the operands is True.
Input : list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1|list2)
Output : TRUE TRUE
NOT operator (!):
A unary operator that negates the status of the elements of the operand.
Input : list1 <- c(0,FALSE)
print(!list1)
Output : TRUE TRUE
Logical AND operator (&&):
Returns True if both the first elements of the operands are True.
Input : list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1 && list2)
Output : FALSE
Compares just the first elements of both the lists.
Logical OR operator (||):
Returns True if either of the first elements of the operands is True.
Input : list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1||list2)
Output : TRUE
The following R code illustrates the usage of all Logical Operators in R:
R
# R program to illustrate
Output:
Element wise AND : FALSE FALSE
Element wise OR : TRUE TRUE
Logical AND : FALSE
Logical OR : TRUE
Negation : TRUE FALSE
Relational Operators
The relational operators carry out comparison operations between the corresponding
elements of the operands. Returns a boolean TRUE value if the first operand satisfies
the relation compared to the second. A TRUE value is always considered to be
greater than the FALSE.
Less than (<):
Returns TRUE if the corresponding element of the first operand is less than that of
the second operand. Else returns FALSE.
Input : list1 <- c(TRUE, 0.1,"apple")
list2 <- c(0,0.1,"bat")
print(list1<list2)
Output : FALSE FALSE TRUE
Less than equal to (<=):
Returns TRUE if the corresponding element of the first operand is less than or equal
to that of the second operand. Else returns FALSE.
Input : list1 <- c(TRUE, 0.1,"apple")
list2 <- c(0,0.1,"bat")
print(list<=list2)
Output : FALSE TRUE TRUE
Greater than (>):
Returns TRUE if the corresponding element of the first operand is greater than that of
the second operand. Else returns FALSE.
Input : list1 <- c(TRUE, 0.1,"apple")
list2 list2)
Output : TRUE FALSE FALSE
R
# R program to illustrate
cat ("Vector1 less than Vector2 :", vec1 < vec2, "\n")
cat ("Vector1 less than equal to Vector2 :", vec1 <= vec2, "\n")
cat ("Vector1 greater than Vector2 :", vec1 > vec2, "\n")
cat ("Vector1 greater than equal to Vector2 :", vec1 >= vec2, "\n")
Output:
Vector1 less than Vector2 : TRUE TRUE
Vector1 less than equal to Vector2 : TRUE TRUE
Vector1 greater than Vector2 : FALSE FALSE
Vector1 greater than equal to Vector2 : FALSE FALSE
Vector1 not equal to Vector2 : TRUE TRUE
Assignment Operators
Assignment operators are used to assigning values to various data objects in R. The
objects may be integers, vectors, or functions. These values are then stored by the
assigned variable names. There are two kinds of assignment operators: Left and
Right
Left Assignment (<- or <<- or =):
Assigns a value to a vector.
Input : vec1 = c("ab", TRUE)
print (vec1)
Output : "ab" "TRUE"
Right Assignment (-> or ->>):
Assigns value to a vector.
Input : c("ab", TRUE) ->> vec1
print (vec1)
Output : "ab" "TRUE"
The following R code illustrates the usage of all Relational Operators in R:
R
# R program to illustrate
vec4 = c(2:5)
Output:
vector 1 : 2 3 4 5
vector 2 : 2 3 4 5
vector 3 : 2 3 4 5
vector 4 : 2 3 4 5
vector 5 : 2 3 4 5
Miscellaneous Operators
These are the mixed operators that simulate the printing of sequences and
assignment of vectors, either left or right-handed.
%in% Operator:
Checks if an element belongs to a list and returns a boolean value TRUE if the value
is present else FALSE.
Input : val <- 0.1
list1 <- c(TRUE, 0.1,"apple")
print (val %in% list1)
Output : TRUE
Checks for the value 0.1 in the specified list. It exists,
therefore, prints TRUE.
Colon Operator(:):
Prints a list of elements starting with the element before the colon to the element
after it.
Input : print (1:5)
Output : 1 2 3 4 5
Prints a sequence of the numbers from 1 to 5.
%*% Operator:
This operator is used to multiply a matrix with its transpose. Transpose of the matrix
is obtained by interchanging the rows to columns and columns to rows. The number
of columns of the first matrix must be equal to the number of rows of the second
matrix. Multiplication of the matrix A with its transpose, B, produces a square
matrix.
R
# R program to illustrate
print(mat)
print("Product of matrices")
print(product,)
Output:
[1] "Matrix elements using : "
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
R – Keywords
R is an open-source programming language that is widely used as a statistical
software and data analysis tool. R generally comes with the Command-line interface.
R is available across widely used platforms like Windows, Linux, and macOS. Also,
the R programming language is the latest cutting-edge tool.
Keywords are specific reserved words in R, each of which has a specific feature
associated with it. Almost all of the words which help one to use the functionality of
the R language are included in the list of keywords. So one can imagine that the list
of keywords is not going to be a small one! In R, one can view these keywords by
using either help(reserved) or ?reserved. Here is the list of keywords in R:
If
else
while
repeat
for
function
in
next
break
TRUE
FALSE
NULL
Inf
NaN
NA
NA_integer
NA_real
NA_complex_
NA_character_
…
Following are some most important keywords along with their examples:
if: If statement is one of the Decision-making statements in the R
programming language. It is one of the easiest decision-making statements. It is
used to decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a block of statement is
executed otherwise not.
Example:
a <- 5
# condition
if( a > 0 )
Output:
Positive Number
else: It is similar to if statement but when the test expression in if condition
fails, then statements in else condition are executed.
Example:
x <- 5
else
Output:
[1] "5 is less than 10"
while: It is a type of control statement which will run a statement or a set of
statements repeatedly unless the given condition becomes false. It is also an
entry controlled loop, in this loop the test condition is tested first, then the body of
the loop is executed, the loop body would not be executed if the test condition is
false.
Example:
val = 1
# statements
print(val)
val = val + 1
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
repeat: It is a simple loop that will run the same statement or a group of
statements repeatedly until the stop condition has been encountered. Repeat loop
does not have any condition to terminate the loop, a programmer must
specifically place a condition within the loop’s body and use the declaration of a
break statement to terminate this loop. If no condition is present in the body of
val = 1
repeat
# statements
print(val)
val = val + 1
if(val > 5)
break
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
# statement
print(val)
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
function: Functions are useful when you want to perform a certain task
multiple number of times. In R functions are created using function keyword.
Example:
evenOdd = function(x){
if(x %% 2 == 0)
return("even")
else
return("odd")
print(evenOdd(4))
print(evenOdd(3))
Output:
[1] "even"
[1] "odd"
next:Next statement in R is used to skip any remaining statements in the loop
and continue the execution of the program. In other words, it is a statement that
skips the current iteration without loop termination.
Example:
# Loop
for (i in val)
if (i == 8)
# test expression
next
print(i)
Output:
[1] 6
[1] 7
[1] 9
[1] 10
[1] 11
break: The break keyword is a jump statement that is used to terminate the
loop at a particular iteration.
Example:
a<-1
print(a)
if(a == 5)
break
a =a +1
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
TRUE/FALSE: The TRUE and FALSE keywords are used to represent a Boolean
true and Boolean false. If the given statement is true, then the interpreter returns
true else the interpreter returns false.
Example:
# A simple R program
# Sample values
x =4
y =3
z =x > y
p =x < y
print(z)
print(p)
Output:
[1] TRUE
[1] FALSE
NULL: In R, NULL represents the null object. NULL is used to represent
missing and undefined values. NULL is the logical representation of a statement
which is neither TRUE nor FALSE.
Example:
# A simple R program
# to illustrate NULL
v = as.null(c(1, 2, 3, 4))
print(v)
Output:
NULL
Inf and NaN: In R is.finite and is.infinite return a vector of the same
length as x, where x is an R object to be tested. This indicating which elements
are finite (not infinite and not missing) or infinite. Inf and -Inf keyword mean
positive and negative infinity whereas NaN keyword means ‘Not a Number’.
# A simple R program
# To check Inf
x = c(Inf, 2, 3)
print(is.finite(x))
# To check NaN
y = c(1, NaN, 3)
print(is.nan(y))
Output:
[1] FALSE TRUE TRUE
[1] FALSE TRUE FALSE
NA: NA stands for “Not Available” and is used to represent missing values.
There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_
of the other atomic vector types which support missing values and all of these are
reserved words in the R language.
# A simple R program
# to illustrate NA
# To check NA
x = c(1, NA, 2, 3)
print(is.na(x))
Output:
[1] FALSE TRUE FALSE FALSE
R – Data Types
Each variable in R has an associated data type. Each data type requires different
amounts of memory and has some specific operations which can be performed over
it. R Programming language has the following basic data types and the following
table shows the data type and the values that each data type can take.
Character “a”, “b”, “c”, …, “@”, “#”, “$”, …., “1”, “2”, …etc
Numeric Datatype
Decimal values are called numerics in R. It is the default data type for numbers in R.
If you assign a decimal value to a variable x as follows, x will be of numeric type.
R
# A simple R program
x = 5.6
print(class(x))
print(typeof(x))
Output:
[1] "numeric"
[1] "double"
Even if an integer is assigned to a variable y, it is still being saved as a numeric
value.
R
# A simple R program
y = 5
print(class(y))
print(typeof(y))
Output:
[1] "numeric"
[1] "double"
When R stores a number in a variable, it converts the number into a “double” value
or a decimal type with at least two decimal places. This means that a value such as
“5” here, is stored as 5.00 with a type of double and a class of numeric. And also y is
not an integer here can be confirmed with the is.integer() function.
R
# A simple R program
y = 5
# is y an integer?
print(is.integer(y))
Output:
[1] FALSE
Integer Datatype
R supports integer data types which are the set of all integers. You can create as well
as convert a value into an integer type using the as.integer() function. You can also
use the capital ‘L’ notation as a suffix to denote that a particular value is of the
integer data type.
R
# A simple R program
x = as.integer(5)
print(class(x))
print(typeof(x))
y = 5L
print(class(y))
print(typeof(y))
Output:
[1] "integer"
[1] "integer"
[1] "integer"
[1] "integer"
Logical Datatype
R has logical data types that take either a value of true or false. A logical value is
often created via a comparison between variables.
R
# A simple R program
# Sample values
x = 4
y = 3
z = x > y
print(z)
print(class(z))
print(typeof())
Output:
[1] TRUE
[1] "logical"
[1] "logical"
Complex Datatype
R supports complex data types that are set of all the complex numbers. The complex
data type is to store numbers with an imaginary component.
R
# A simple R program
x = 4 + 3i
print(class(x))
print(typeof(x))
Output:
[1] "complex"
[1] "complex"
Character Datatype
R supports character data types where you have all the alphabets and special
characters. It stores character values or strings. Strings in R can contain alphabets,
numbers, and symbols. The easiest way to denote that a value is of character type in
R is to wrap the value inside single or double inverted commas.
R
# A simple R program
char = "Geeksforgeeks"
print(class(char))
print(typeof(char))
Output:
[1] "character"
[1] "character"
There are several tasks that can be done using data types. Let’s understand each
task with its action and the syntax for doing the task along with an R code to
illustrate the task.
# A simple R program
# Logical
print(class(TRUE))
# Integer
print(class(3L))
# Numeric
print(class(10.5))
# Complex
print(class(1+2i))
# Character
print(class("12-04-2020"))
Output:
[1] "logical"
[1] "integer"
[1] "numeric"
[1] "complex"
[1] "character"
Type verification
To do that, you need to use the prefix “is.” before the data type as a command. The
syntax for that is, is.data_type() of the object you have to verify.
Syntax:
is.data_type(object)
Example:
R
# A simple R program
# Logical
print(is.logical(TRUE))
# Integer
print(is.integer(3L))
# Numeric
print(is.numeric(10.5))
# Complex
print(is.complex(1+2i))
# Character
print(is.character("12-04-2020"))
print(is.integer("a"))
print(is.numeric(2+3i))
Output:
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE
# A simple R program
# Logical
print(as.numeric(TRUE))
# Integer
print(as.complex(3L))
# Numeric
print(as.logical(10.5))
# Complex
print(as.character(1+2i))
# Can't possible
print(as.numeric("12-04-2020"))
Output:
[1] 1
[1] 3+0i
[1] TRUE
[1] "1+2i"
[1] NA
Warning message:
In print(as.numeric("12-04-2020")) : NAs introduced by coercion