R – Data Structures
R – Data Structures
November 14, 2022 R: Data Structures 2
Vectors - Definition
•Basic data structures in R programming.
•Only contains elements of the same data type, so it is
homogeneous
•Data types can be numeric, integer, character,
complex or logical.
•The elements in the vector are components
•Created using c() function
•To check the type of vector by using typeof() function.
November 14, 2022 R: Data Structures 3
Types of Vectors
1. Atomic Vectors - all the elements are of the same
data type
2. Lists - the elements are of different data types
Vector length
•To find the number of elements in a vector by using
length() function
November 14, 2022 R: Data Structures 4
Creating Vectors
1. Using c() function
•This function returns a one-dimensional array or
simply vector.
•The c() function is a generic function which combines
its argument.
•All arguments are restricted with a common data type
which is the type of the returned value.
> x <- c(1,2,3,4,5) #creates a vector named x
>x #prints the vector x
November 14, 2022 R: Data Structures 5
Creating Vectors
2. Using the colon(:) operator
Syntax
z=x:y
This operator creates a vector with elements from x to
y and assigns it to z.
November 14, 2022 R: Data Structures 6
Creating Vectors
3. Using the seq() function
•A sequence function creates a sequence of elements
as a vector.
•The seq() function is used in two ways, i.e., by setting
step size with ’by' parameter or specifying the length
of the vector with the '[Link]' feature.
November 14, 2022 R: Data Structures 7
Atomic Vectors
Four Types of Atomic Vectors
1. Numeric vector
•The decimal values are called as numeric data types in
R.
•A vector which contains numeric elements is known as
a numeric vector.
November 14, 2022 R: Data Structures 8
Atomic Vectors
2. Integer vector
•A numeric value without a decimal point is known as integer
data.
•This integer data is represented by "Int."
•The Int size is 2 bytes and long Int size of 4 bytes.
•There is two way to assign an integer value to a variable, i.e.,
by using [Link]() function and appending of L to the
value.
•A vector which contains integer elements is known as an
integer vector.
November 14, 2022 R: Data Structures 9
Atomic Vectors
3. Character vector
•A character is held as a one-byte integer in memory.
•In R, there are two different ways to create a character
data type value
•Using [Link]() function and by typing string between
double quotes("") or single quotes('')
•A vector which contains character elements is known as
character vector
November 14, 2022 R: Data Structures 10
Atomic Vectors
4. Logical Vector
• The logical data types have only two values i.e., True
or False.
• These values are based on which condition is
satisfied.
• A vector which contains Boolean values is known as
the logical vector.
November 14, 2022 R: Data Structures 11
Accessing Elements of Vectors
•Elements of a vector is accessed with the help of
vector indexing.
•Indexing denotes the position where the value in
a vector is stored.
•Indexing will be performed with the help of
integer, character, or logic.
November 14, 2022 R: Data Structures 12
1) Indexing with integer vector
•In R, the indexing starts from 1, whereas in C, C++ and java
the indexing starts from 0
•Perform indexing by specifying an integer value in square
braces [] next to our vector.
Example:
seq_vec<-seq(1,4,[Link]=6)
seq_vec
seq_vec[2]
Output
[1] 1.0 1.6 2.2 2.8 3.4 4.0 [1] 1.6
November 14, 2022 R: Data Structures 13
2) Indexing with a character vector
• In character vector indexing, we assign a unique key to each
element of the vector.
• These keys are uniquely defined as each element and can be
accessed very easily.
Example:
char_vec<-c("Ram"=25,"Arun"=23,"Raja"=30)
char_vec
char_vec["Arun"]
Output
Ram Arun Raja 25 23 30 Arun 23
November 14, 2022 R: Data Structures 14
3) Indexing with a logical vector
•In logical indexing, it returns the values of those
positions whose corresponding position has a logical
vector TRUE.
Example:
a<-c(1,2,3,4,5,6)
a[c(TRUE,FALSE,TRUE,TRUE,FALSE,TRUE)]
Output
[1] 1 3 4 6
November 14, 2022 R: Data Structures 15
Vector operations
1) Combining vectors
• The c() function is not only used to create a vector, but also used to
combine two vectors.
• By combining one or more vectors, it forms a new vector which
contains all the elements of each vector.
• Example:
• x<-c(1,2,3,4,5,6)
• y<-c("aaa","bbb","ccc","ddd","eee","fff")
• z<-c(x,y)
November 14, 2022 R: Data Structures 16
2) Arithmetic operations
• We can perform all the arithmetic operation on vectors.
• The arithmetic operations are performed member-by-member on
vectors.
• We can add, subtract, multiply, or divide two vectors.
• Example:
a<-c(1,3,5,7)
b<-c(2,4,6,8)
a+b
a-b
a/b
a%%b
November 14, 2022 R: Data Structures 17
2a) Vector Element Recycling
• If we apply arithmetic operations to two vectors of unequal length, then
the elements of the shorter vector are recycled to complete the operations.
x=c(3,8,4,5,0,11)
y=c(4,11)
# y becomes c(4,11,4,11,4,11)
z=x+y
z
z=x-y
z
[1] 7 19 8 16 4 22
[1] -1 -3 0 -6 -4 0
November 14, 2022 R: Data Structures 18
2b) Vector Element Sorting
• Elements in a vector can be sorted using the sort() function.
x=c(56,76,32,12,-6,98,-87,45)
y=sort(x)
y
[1] -87 -6 12 32 45 56 76 98
# Sort the elements in the reverse order.
y=sort(x,decreasing=TRUE)
y
[1] 98 76 56 45 32 12 -6 -87
November 14, 2022 R: Data Structures 19
3) Logical Index vector
• With the help of the logical index vector in R, we can form a new
vector from a given vector.
• This vector has the same length as the original vector. The vector
members are TRUE only when the corresponding members of the
original vector are included in the slice; otherwise, it will be false.
• Example
a<-c(“aaa",”bbb",”ccc",”ddd",”eee",”fff")
b<-c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE)
a[b]
[1] “aaa” “ccc" “ddd"
November 14, 2022 R: Data Structures 20
4) Duplicate Index
•An index vector allows duplicate values which means we can
access one element twice in one operation.
Example:
q<-c(“aaa",”bbb",”ccc",”ddd",”eee",”fff")
q[c(2,4,4,3)]
[1] "bbb" "ddd" "ddd" "ccc"
November 14, 2022 R: Data Structures 21
5) Range Indexes
•Range index is used to slice a vector to form a new vector.
•For slicing, we used colon(:) operator.
•Range indexes are very helpful for the situation involving a
large operator.
Example:
q<-c(“aaa",“bbb",“ccc",“ddd",“eee",“fff")
b<-q[2:5]
b
[1] “bbb“ “ccc“ “ddd“ “eee"
November 14, 2022 R: Data Structures 22
6) Out-of-order Indexes
•In R, the index vector can be out-of-order.
•Below is an example in which a vector slice with the
order of first and second values reversed.
•Example:
•q<-c(“aaa",”bbb",”ccc",”ddd",”eee",”fff")
•q[c(2,1,3,4,5,6)]
•[1] "bbb" "aaa" "ccc" "ddd" "eee" "fff"
November 14, 2022 R: Data Structures 23
7) Named vectors members
• First create vector of characters as:
z=c(“R”, “Programming)
z
• Then, name the first vector member as “First” and the second
member as “Second”.
names(v) = c("First", "Second")
v
• To retrieve the first member by its name as follows:
v["First"]
• Also reverse the order using the character string index vector:
v[c("Second", "First")]
November 14, 2022 R: Data Structures 24
Lists Definition
•In R, lists are the second type of vector.
•Lists are the objects of R
•Contain elements of different types such as number,
vectors, string and another list inside it.
• It can also contain a function or a matrix as its
elements.
•A list is a data structure which has components of
mixed data types.
•List is a generic vector which contains other objects.
November 14, 2022 R: Data Structures 25
List Creation
•In R, the vector is created with the help of c()
function.
•Like c() function, there is another function, i.e.,
list() is used to create a list in R.
Syntax
list()
•List can be created with same data type or with
different data type
November 14, 2022 R: Data Structures 26
Naming List elements
•R provides a very easy way for accessing elements, i.e., by
giving the name to each element of a list.
•By assigning names to the elements, we can access the
element easily.
•There are only three steps to print the list data
corresponding to the name:
1. Creating a list.
2. Assign a name to the list elements with the help of
names() function.
3. Print the list data.
November 14, 2022 R: Data Structures 27
Naming List elements
• # Creating a list containing a vector, a matrix and a list.
list_data<- list(c("Rama","Arun","Sita"), matrix(c(40,80,60,70,90,80),
nrow = 2), list("BCA","MCA","[Link]"))
• # Giving names to the elements in the list.
names(list_data) <- c("Students", "Marks", "Course")
• # Show the list.
print(list_data)
November 14, 2022 R: Data Structures 28
Accessing List Elements
•Two ways, we can access the elements of a list.
•First one is the indexing method performed in the same way
as a vector.
•In the second one, we can access the elements of a list with
the help of names.
•It will be possible only with the named list.; we cannot access
the elements of a list using names if the list is normal.
1. By using index
2. By using names
November 14, 2022 R: Data Structures 29
Manipulation of list elements
•R allows us to add, delete, or update elements in the
list.
•We can update an element of a list from anywhere,
but elements can add or delete only at the end of the
list.
•To remove an element from a specified index, we will
assign it a null value.
• We can update the element of a list by overriding it
from the new value.
November 14, 2022 R: Data Structures 30
Converting list to vector
•Cannot perform all the arithmetic operations on list
elements. This is a drawback of using list
•To remove this drawback, R provides unlist() function.
•This function converts the list into vectors.
•In some cases, it is required to convert a list into a vector so
that we can use the elements of the vector for further
manipulation.
•The unlist() function takes the list as a parameter and change
into a vector.
November 14, 2022 R: Data Structures 31
Merging Lists
• R allows us to merge one or more lists into one list.
• Merging is done with the help of the list() function also.
• To merge the lists, we have to pass all the lists into list function as a
parameter, and it returns a list which contains all the elements which are
present in the lists.
Example
# Creating two lists.
Even_list <- list(2,4,6,8,10)
Odd_list <- list(1,3,5,7,9)
# Merging the two lists.
[Link] <- list(Even_list,Odd_list)
# Printing the merged list.
print([Link])
November 14, 2022 R: Data Structures 32
Arrays - Definition
• R arrays are data objects that store data in more than two
dimensions.
• Homogeneous in nature. They can store values of a single basic data
type only.
• They store the data in the form of layered matrices.
• An array is created with the help of the array() function.
• This array() function takes a vector as an input and to create an array
it uses vectors values in the dim parameter.
• For example- if we will create an array of dimension (2, 3, 4) then it
will create 4 rectangular matrices of 2 row and 3 columns.
November 14, 2022 R: Data Structures 33
R Array Syntax
array_name <- array(data, dim= (row_size, column_size, matrices, dim_names))
data
• The data is the first argument in the array() function. It is an input vector which is
given to the array.
matrices
• In R, the array consists of multi-dimensional matrices.
row_size
• This parameter defines the number of row elements which an array can store.
column_size
• This parameter defines the number of columns elements which an array can store.
dim_names
• This parameter is used to change the default names of rows and columns.
November 14, 2022 R: Data Structures 34
Array Creation
• Arrays are created using vector and array() function.
• In array, data is stored in the form of the matrix.
Two steps to create a matrix
• In the first step, we will create two vectors of different lengths.
• Once our vectors are created, we take these vectors as inputs to
the array.
# Create two vectors of different lengths.
vector1=c(10,20,30)
vector2=c(5,6,7,8,9,10)
# Take these vectors as input to the array.
result <- array(c(vector1,vector2),dim = c(3,3,2))
print(result)
November 14, 2022 R: Data Structures 35
Naming Columns and Rows
•In R, we can give the names to the rows, columns, and
matrices of the array.
•This is done with the help of the dim name parameter
of the array() function.
•It is not necessary to give the name to the rows and
columns.
•It is only used to differentiate the row and column for
better understanding.
November 14, 2022 R: Data Structures 36
Accessing Array elements
•Like C or C++, we can access the elements of the
array.
•The elements are accessed with the help of the index.
•Simply, we can access the elements of the array with
the help of the indexing method.
November 14, 2022 R: Data Structures 37
Manipulating Array Elements
•The array is made up matrices in multiple
dimensions so that the operations on elements
of an array are carried out by accessing elements
of the matrices.
November 14, 2022 R: Data Structures 38
Calculations across Array elements
• For calculation purpose, r provides apply() function.
• This apply function contains three parameters i.e., x, margin, and
function.
• This function takes the array on which we have to perform the
calculations.
Syntax
apply(x, margin, fun)
• Here, x is an array, and a margin is the name of the dataset which is
used and fun is the function which is to be applied to the elements of
the array.
November 14, 2022 R: Data Structures 39
Matrix - Definition
• In R, a two-dimensional rectangular data set is known as a matrix.
• A matrix is created with the help of the vector input to the matrix
function.
• On R matrices, we can perform addition, subtraction, multiplication,
and division operation.
• In the R matrix, elements are arranged in a fixed number of rows and
columns.
• The matrix elements are the real numbers. In R, we use matrix
function, which can easily reproduce the memory representation of
the matrix.
• In the R matrix, all the elements must share a common basic type.
November 14, 2022 R: Data Structures 40
•A Matrix is created using the matrix() function
Syntax
matrix(data, nrow, ncol, byrow, dimnames)
•data is the input vector which becomes the data elements of
the matrix.
•nrow is the number of rows to be created.
•ncol is the number of columns to be created.
•byrow is a logical clue. If TRUE then the input vector
elements are arranged by row.
•dimname is the names assigned to the rows and columns.
November 14, 2022 R: Data Structures 41
Matrix Creation
• Like vector and list, R provides the matrix() function to create a
matrix.
• This function plays an important role in data analysis.
Example
#Arranging elements sequentially by row.
P <- matrix(c(5:16), nrow = 4, byrow = TRUE)
print(P)
# Arranging elements sequentially by column.
Q <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(Q)
November 14, 2022 R: Data Structures 42
Accessing Matrix Elements in R
•Three ways to access the elements from the matrix.
1. Access the element which presents on nth row and
mth column.
2. Access all the elements of the matrix which are
present on the nth row.
3. Access all the elements of the matrix which are
present on the mth column.
November 14, 2022 R: Data Structures 43
Matrix Operations
•Matrix Addition
•Matrix Subtraction
•Matrix Multiplication
•Multiplication by Constant
•Matrix Division
November 14, 2022 R: Data Structures 44
Factors
•Factors are the data objects which are used to categorize the
data and store it as levels.
•They can store both strings and integers.
•They are useful in the columns which have a limited number
of unique values.
•Like "Male, "Female" and True, False etc. They are useful in
data analysis for statistical modeling.
•Factors are created using the factor() function by taking a
vector as input.
November 14, 2022 R: Data Structures 45
Attributes of a factor
•X
It is the input vector which is to be transformed into a factor.
• levels
It is an input vector that represents a set of unique values which are
taken by x.
• labels
It is a character vector which corresponds to the number of labels.
• Exclude
It is used to specify the value which we want to be excluded,
• ordered
It is a logical attribute which determines if the levels are ordered.
• nmax
It is used to specify the upper bound for the maximum number of
level.
November 14, 2022 R: Data Structures 46
How to create a factor?
•A factor is created in two steps
•In the first step, we create a vector.
•Next step is to convert the vector into a factor
•R provides factor() function to convert the vector into
factor.
Syntax of factor function
factor_data<- factor(vector)
November 14, 2022 R: Data Structures 47
Accessing components of factor
• The process of accessing components of factor is much more similar to the vectors.
• We can access the element with the help of the indexing method or using logical vectors.
# Creating a vector as input.
data <- c("aaa","bbb","ccc","bbb","aaa","ddd","bbb","aaa","ddd","ccc","ddd")
# Applying the factor function.
factor_data<- factor(data)
#Printing all elements of factor
print(factor_data)
#Accessing 4th element of factor
print(factor_data[4])
#Accessing 5th and 7th element
print(factor_data[c(5,7)])
#Accessing all element except 4th one
print(factor_data[-4])
#Accessing elements using logical vector
print(factor_data[c(TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,TRUE)])
November 14, 2022 R: Data Structures 48
Changing the Order of Levels
• The order of the levels in a factor can be changed by applying the
factor function again with new order of the levels.
data <- c("East","West","East","North","North","East","West",
"West","West","East","North")
# Create the factors
factor_data <- factor(data)
print(factor_data)
# Apply the factor function with required order of the level.
new_order_data <- factor(factor_data,levels =
c("East","West","North"))
print(new_order_data)
November 14, 2022 R: Data Structures 49
Generating Factor Levels
•Generate factor levels by using the gl() function.
•It takes two integers as input which indicates how many
levels and how many times each level.
Syntax
gl(n, k, labels)
•n is a integer giving the number of levels.
•k is a integer giving the number of replications.
•labels is a vector of labels for the resulting factor levels.
November 14, 2022 R: Data Structures 50
Data Frames
• A data frame is a two-dimensional array-like structure or a table in
which a column contains values of one variable, and rows contains
one set of values from each column.
• A data frame is a special case of the list in which each component has
equal length.
• A data frame is used to store data table and the vectors which are
present in the form of a list in a data frame, are of equal length.
• In a simple way, it is a list of equal length vectors.
• A matrix can contain one type of data, but a data frame can contain
different data types such as numeric, character, factor, etc.
November 14, 2022 R: Data Structures 51
Data Frames
Characteristics of a data frame
•The columns name should be non-empty.
•The rows name should be unique.
•The data which is stored in a data frame can be a
factor, numeric, or character type.
•Each column contains the same number of data items.
November 14, 2022 R: Data Structures 52
How to create Data Frame?
•In R, the data frames are created with the help of
frame() function of data.
•This function contains the vectors of any type such as
numeric, character, or integer.
•Example, we create a data frame that contains
employee id (integer vector), employee
name(character vector), salary(numeric vector), and
starting date(Date vector).
November 14, 2022 R: Data Structures 53
Getting the structure of R Data Frame
•In R, we can find the structure of our data frame.
•R provides an built-in function called str() which
returns the data with its complete structure.
•Example, we have created a frame using a vector of
different data type and extracted the structure of it.
November 14, 2022 R: Data Structures 54
Summary of data in Data Frames
•In some cases, it is required to find the statistical
summary and nature of the data in the data frame.
•R provides the summary() function to extract the
statistical summary and nature of the data.
•This function takes the data frame as a parameter and
returns the statistical information of the data.
November 14, 2022 R: Data Structures 55
Extracting data from Data Frame
•The data in the data frame is very essential for us.
•To manipulate the data in the data frame, it is essential to
extract it from the data frame.
Extract the data in three ways:
•Extract the specific columns from a data frame using the
column name.
•Extract the specific rows from a data frame.
•Extract the specific rows corresponding to specific columns.
November 14, 2022 R: Data Structures 56
Modification in Data Frame
• R allows us to do modification in our data frame.
• Like matrices modification, we can modify our data frame through
re-assignment.
• We cannot only add rows and columns, but also we can delete them.
The data frame is expanded by adding rows and columns.
• Add a column by adding a column vector with the help of a new
column name using cbind() function.
• Add rows by adding new rows in the same structure as the existing
data frame and using rbind() function
• Delete the columns by assigning a NULL value to them.
• Delete the rows by re-assignment to them.
November 14, 2022 R: Data Structures 57