Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

basic-syntax-in-r-programming

The document provides an overview of basic syntax in R programming, including how to write and execute simple programs, use variables, comments, and keywords. It explains the types of operators available in R, such as arithmetic, logical, and relational operators, along with examples of their usage. Additionally, it discusses the importance of comments for code readability and the specific syntax for single-line comments in R.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

basic-syntax-in-r-programming

The document provides an overview of basic syntax in R programming, including how to write and execute simple programs, use variables, comments, and keywords. It explains the types of operators available in R, such as arithmetic, logical, and relational operators, along with examples of their usage. Additionally, it discusses the importance of comments for code readability and the specific syntax for single-line comments in R.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

lOMoARcPSD|34377590

Basic Syntax in R Programming

pharmaceutical Engineering Unit 3 (Jawaharlal Nehru Technological University,


Hyderabad)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)
lOMoARcPSD|34377590

Basic Syntax in R Programming


$ R
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:
Rscript myFile.R

Output:
[1] "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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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.

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

 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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

someone referring to the source code.


Just like python single-line comments, any statement starting with “#” is a comment in R.
Syntax:
# comment statement
Example 1:

# 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:

# R program to add two numbers

# Assigning values to variables

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.

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

This makes the process of commenting a block of code easier and faster than adding # before
each line one at a time.

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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 (^):

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

The first operand is raised to the power of the second operand.


Input : list1 <- c(2, 3)
list2 <- c(2,4)
print(list1^list2)
Output : 4 81
Modulo Operator (%%):
The remainder of the first operand divided by the second operand is returned.
Input : list1<- c(2, 3)
list2<-c(2,4)
print(list1%%list2)
Output : 0 3
The following R code illustrates the usage of all Arithmetic Operators in R:

 R

# R program to illustrate

# the use of Arithmetic operators

vec1 <- c(0, 2)

vec2 <- c(2, 3)

# Performing operations on Operands

cat ("Addition of vectors :", vec1 + vec2, "\n")

cat ("Subtraction of vectors :", vec1 - vec2, "\n")

cat ("Multiplication of vectors :", vec1 * vec2, "\n")

cat ("Division of vectors :", vec1 / vec2, "\n")

cat ("Modulo of vectors :", vec1 %% vec2, "\n")

cat ("Power operator :", vec1 ^ vec2)

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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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

# the use of Logical operators

vec1 <- c(0,2)

vec2 <- c(TRUE,FALSE)

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# Performing operations on Operands

cat ("Element wise AND :", vec1 & vec2, "\n")

cat ("Element wise OR :", vec1 | vec2, "\n")

cat ("Logical AND :", vec1 && vec2, "\n")

cat ("Logical OR :", vec1 || vec2, "\n")

cat ("Negation :", !vec1)

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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

Greater than equal to (>=):


Returns TRUE if the corresponding element of the first operand is greater or equal to
that of the second operand. Else returns FALSE.
Input : list1 <- c(TRUE, 0.1,"apple")
list2 =list2)
Output : TRUE TRUE FALSE
Not equal to (!=):
Returns TRUE if the corresponding element of the first operand is not equal to the
second operand. Else returns FALSE.
Input : list1 <- c(TRUE, 0.1,""apple")
list2 <- c(0,0.1,"bat")
print(list1!=list2)
Output : TRUE FALSE TRUE
The following R code illustrates the usage of all Relational Operators in R:

 R

# R program to illustrate

# the use of Relational operators

vec1 <- c(0, 2)

vec2 <- c(2, 3)

# Performing operations on Operands

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")

cat ("Vector1 not 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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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

# the use of Assignment operators

vec1 <- c(2:5)

c(2:5) ->> vec2

vec3 <<- c(2:5)

vec4 = c(2:5)

c(2:5) -> vec5

# Performing operations on Operands

cat ("vector 1 :", vec1, "\n")

cat("vector 2 :", vec2, "\n")

cat ("vector 3 :", vec3, "\n")

cat("vector 4 :", vec4, "\n")

cat("vector 5 :", vec5)

Output:

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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.

Input : mat = matrix(c(1,2,3,4,5,6),nrow=2,ncol=3)


print (mat)
print( t(mat))
pro = mat %*% t(mat)
print(pro)
Output : [,1] [,2] [,3] #original matrix of order 2x3
[1,] 1 3 5
[2,] 2 4 6
[,1] [,2] #transposed matrix of order 3x2
[1,] 1 2
[2,] 3 4
[3,] 5 6
[,1] [,2] #product matrix of order 2x2
[1,] 35 44
[2,] 44 56
The following R code illustrates the usage of all Miscellaneous Operators in R:

 R

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# R program to illustrate

# the use of Miscellaneous operators

mat <- matrix (1:4, nrow = 1, ncol = 4)

print("Matrix elements using : ")

print(mat)

product = mat %*% t(mat)

print("Product of matrices")

print(product,)

cat ("does 1 exist in prod matrix :", "1" %in% product)

Output:
[1] "Matrix elements using : "
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4

[1] "Product of matrices"


[,1]
[1,] 30

does 1 exist in prod matrix : FALSE

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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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:

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# R program to illustrate if statement

# assigning value to variable a

a <- 5

# condition

if( a > 0 )

print("Positive Number") # Statement

 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

# Check value is less than or greater than 10

if(x > 10)

print(paste(x, "is greater than 10"))

else

print(paste(x, "is less than 10"))

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

 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:

# R program to demonstrate the use of while loop

val = 1

# using while loop

while (val <= 5 )

# 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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

the repeat loop then it will iterate infinitely.


Example:

# R program to demonstrate the use of repeat loop

val = 1

# using repeat loop

repeat

# statements

print(val)

val = val + 1

# checking stop condition

if(val > 5)

# using break statement

# to terminate the loop

break

 Output:
 [1] 1
 [1] 2
 [1] 3
 [1] 4
 [1] 5

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

 for: It is a type of control statement that enables one to easily construct a


loop that has to run statements or a set of statements multiple times. For loop is
commonly used to iterate over items of a sequence. It is 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:

# R program to demonstrate the use of for loop

# using for loop

for (val in 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:

# A simple R function to check

# whether x is even or odd

evenOdd = function(x){

if(x %% 2 == 0)

return("even")

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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:

# R program to illustrate next in for loop

val <- 6:11

# Loop

for (i in val)

if (i == 8)

# test expression

next

print(i)

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

 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:

# R Break Statement Example

a<-1

while (a < 10)

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:

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# A simple R program

# to illustrate TRUE / FALSE

# Sample values

x =4

y =3

# Comparing two values

z =x > y

p =x < y

# print the logical value

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)

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

 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 illustrate Inf and NaN

# 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))

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

 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.

Data Types in R Programming Language:

Basic Data Types Values

Numeric Set of all real numbers

Integer Set of all integers, Z

Logical TRUE and FALSE

Complex Set of complex numbers

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

# to illustrate Numeric data type

# Assign a decimal value to x

x = 5.6

# print the class name of variable

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

print(class(x))

# print the type of variable

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

# to illustrate Numeric data type

# Assign an integer value to y

y = 5

# print the class name of variable

print(class(y))

# print the type of variable

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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

“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

# to illustrate Numeric data type

# Assign a integer value to y

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

# to illustrate integer data type

# Create an integer value

x = as.integer(5)

# print the class name of x

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

print(class(x))

# print the type of x

print(typeof(x))

# Declare an integer by appending an L suffix.

y = 5L

# print the class name of y

print(class(y))

# print the type of 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

# to illustrate logical data type

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# Sample values

x = 4

y = 3

# Comparing two values

z = x > y

# print the logical value

print(z)

# print the class name of z

print(class(z))

# print the type of 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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# to illustrate complex data type

# Assign a complex value to x

x = 4 + 3i

# print the class name of x

print(class(x))

# print the type of 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

# to illustrate character data type

# Assign a character value to char

char = "Geeksforgeeks"

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# print the class name of char

print(class(char))

# print the type of 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.

Find data type of an object


To find the data type of an object you have to use class() function. The syntax for
doing that is you need to pass the object as an argument to the function class() to
find the data type of an object.
Syntax:
class(object)
Example:
 R

# A simple R program

# to find data type of an object

# Logical

print(class(TRUE))

# Integer

print(class(3L))

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

# 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

# Verify if an object is of a certain datatype

# Logical

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

Coerce or convert the data type of an object to


another
This task is interesting where you can change or convert the data type of one object
to another. To perform this action you have to use the prefix “as.” before the data
type as the command. The syntax for doing that is as.data_type() of the object
which you want to coerce.
Syntax:
as.data_type(object)
Note: All the coercions are not possible and if attempted will be returning an “NA”
value.
Example:
 R

# A simple R program

# convert data type of an object to another

# 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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)


lOMoARcPSD|34377590

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

Downloaded by Chelakapalli Likhitha (likhithachelakapalli@gmail.com)

You might also like