Unit 2 Notes - Data Analysis Using r
Unit 2 Notes - Data Analysis Using r
UNIT 2
R - Data Types
In contrast to other programming languages like C and java in R, the variables are not declared
as some data type. The variables are assigned with R-Objects and the data type of the R-object
becomes the data type of the variable. There are many types of R-objects. The frequently used
ones are −
Vectors
Lists
Matrices
Arrays
Factors
Data Frames
The simplest of these objects is the vector object and there are six data types of these atomic
vectors, also termed as six classes of vectors.
In R programming, the very basic data types are the R-objects called vectors which hold
elements of different classes as shown above. Please note in R the number of classes is not
confined to only the above six types. For example, we can use many atomic vectors and create an
array whose class will become array.
1. Vectors
When you want to create vector with more than one element, you should use c() function which
means to combine the elements into a vector.
# Create a vector.
print(apple)
# Get the class of the vector.
print(class(apple))
[1] "character"
2. Lists
A list is an R-object which can contain many different types of elements inside it like vectors,
functions and even another list inside it.
# Create a list.
print(list1)
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
3. Matrices
A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the
matrix function.
# Create a matrix.
print(M)
When we execute the above code, it produces the following result −
4. Arrays
While matrices are confined to two dimensions, arrays can be of any number of dimensions. The
array function takes a dim attribute which creates the required number of dimension. In the
below example we create an array with two elements which are 3x3 matrices each.
# Create an array.
print(a)
,,1
,,2
Factors are the r-objects which are created using a vector. It stores the vector along with the
distinct values of the elements in the vector as labels. The labels are always character irrespective
of whether it is numeric or character or Boolean etc. in the input vector. They are useful in
statistical modeling.
Factors are created using the factor() function. The nlevels functions gives the count of levels.
# Create a vector.
print(factor_apple)
print(nlevels(factor_apple))
[1] 3
5. Data Frames
Data frames are tabular data objects. Unlike a matrix in data frame each column can contain
different modes of data. The first column can be numeric while the second column can be
character and third column can be logical. It is a list of vectors of equal length.
Age = c(42,38,26)
print(BMI)
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26
R – Variables
A variable provides us with named storage that our programs can manipulate. A variable in R
can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid
variable name consists of letters, numbers and the dot or underline characters. The variable name
starts with a letter or the dot not followed by a number.
1. Variable Assignment
The variables can be assigned values using leftward, rightward and equal to operator. The values
of the variables can be printed using print() or cat() function. The cat() function combines
multiple items into a continuous print output.
var.1 = c(0,1,2,3)
print(var.1)
[1] 0 1 2 3
var.1 is 0 1 2 3
var.2 is learn R
var.3 is 1 1
In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object
assigned to it. So R is called a dynamically typed language, which means that we can change a
variable’s data type of the same variable again and again when using it in a program.
3. Finding Variables
To know all the variables currently available in the workspace we use the ls() function. Also the
ls() function can use patterns to match the variable names.
print(ls())
The ls() function can use patterns to match the variable names.
print(ls(pattern = "var"))
The variables starting with dot(.) are hidden, they can be listed using "all.names = TRUE"
argument to ls() function.
print(ls(all.name = TRUE))
4. Deleting Variables
Variables can be deleted by using the rm() function. Below we delete the variable var.3. On
printing the value of the variable error is thrown.
rm(var.3)
print(var.3)
All the variables can be deleted by using the rm() and ls() function together.
rm(list = ls())
print(ls())
character(0)
R – Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. R language is rich in built-in operators and provides following types of operators.
Types of Operators
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Miscellaneous Operators
Arithmetic Operators
Following table shows the arithmetic operators supported by R language. The operators act on
each element of the vector.
[1] 0 1 1
^ The first vector raised to the v <- c( 2,5.5,6)
exponent of second vector t <- c(8, 3, 4)
print(v^t)
it produces the following result −
Relational Operators
Following table shows the relational operators supported by R language. Each element of the
first vector is compared with the corresponding element of the second vector. The result of
comparison is a Boolean value.
Logical Operators
Following table shows the logical operators supported by R language. It is applicable only to
vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical
value TRUE.
Each element of the first vector is compared with the corresponding element of the second
vector. The result of comparison is a Boolean value.
Operator Description Example
& It is called Element-wise v <- c(3,1,TRUE,2+3i)
Logical AND operator. It t <- c(4,1,FALSE,2+3i)
combines each element of the print(v&t)
first vector with the it produces the following result −
corresponding element of the
second vector and gives a [1] TRUE TRUE FALSE TRUE
output TRUE if both the
elements are TRUE.
| It is called Element-wise <- c(3,0,TRUE,2+2i)
Logical OR operator. It t <- c(4,0,FALSE,2+3i)
combines each element of the print(v|t)
first vector with the it produces the following result −
corresponding element of the
second vector and gives a [1] TRUE FALSE TRUE TRUE
output TRUE if one the
elements is TRUE.
! It is called Logical NOT v <- c(3,0,TRUE,2+2i)
operator. Takes each element of print(!v)
the vector and gives the it produces the following result −
opposite logical value.
[1] FALSE TRUE FALSE FALSE
The logical operator && and || considers only the first element of the vectors and give a vector of
single element as output.
&& Called Logical AND operator. v <- c(3,0,TRUE,2+2i)
Takes first element of both the t <- c(1,3,TRUE,2+3i)
vectors and gives the TRUE print(v&&t)
only if both are TRUE. it produces the following result −
[1] TRUE
|| Called Logical OR operator. v <- c(0,0,TRUE,2+2i)
Takes first element of both the t <- c(0,3,TRUE,2+3i)
vectors and gives the TRUE if print(v||t)
one of them is TRUE. it produces the following result −
[1] FALSE
R - Decision making
Decision making structures require the programmer to specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
1. R - If Statement
if(boolean_expression)
If the Boolean expression evaluates to be true, then the block of code inside the if statement will
be executed. If Boolean expression evaluates to be false, then the first set of code after the end of
the if statement (after the closing curly brace) will be executed.
Example
x <- 30L
if(is.integer(x)) {
print("X is an Integer")
When the above code is compiled and executed, it produces the following result −
2. R - If...Else Statement
An if statement can be followed by an optional else statement which executes when the boolean
expression is false.
if(boolean_expression) {
} else {
Example
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
When the above code is compiled and executed, it produces the following result −
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if, else if, else statements there are few points to keep in mind.
An if can have zero or one else and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
if(boolean_expression 1) {
} else {
Example
x <- c("what","is","truth")
if("Truth" %in% x) {
} else {
When the above code is compiled and executed, it produces the following result −
4. R - Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.
In the case of no match, if there is a unnamed element of ... its value is returned. (If there is more
than one such argument an error is returned.)
Example
x <- switch(
3,
"first",
"second",
"third",
"fourth"
print(x)
When the above code is compiled and executed, it produces the following result −
[1] "third"
R – Loops
A loop statement allows us to execute a statement or group of statements multiple times and the
following is the general form of a loop statement in most of the programming languages.
A loop statement allows us to execute a statement or group of statements multiple times and
the following is the general form of a loop statement in most of the programming languages.
1. R - Repeat Loop
The Repeat loop executes the same code again and again until a stop condition is met.
repeat {
commands
if(condition) {
break
Example
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
if(cnt > 5) {
break
When the above code is compiled and executed, it produces the following result −
2. R - While Loop
The While loop executes the same code again and again until a stop condition is met.
while (test_expression)
{
statement
Here key point of the while loop is that the loop might not ever run. When the condition is tested
and the result is false, the loop body will be skipped and the first statement after the while loop
will be executed.
Example
cnt <- 2
print(v)
cnt = cnt + 1
When the above code is compiled and executed, it produces the following result −
3. R - For Loop
A For loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
statements
R’s for loops are particularly flexible in that they are not limited to integers, or even numbers in
the input. We can pass character vectors, logical vectors, lists or expressions.
Example
v <- LETTERS[1:4]
for ( i in v) {
print(i)
When the above code is compiled and executed, it produces the following result −
[1] "A"
[1] "B"
[1] "C"
[1] "D"