0% found this document useful (0 votes)
4 views30 pages

r22 Unit3 Vector Matrix

Uploaded by

227r1a67a3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views30 pages

r22 Unit3 Vector Matrix

Uploaded by

227r1a67a3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

In R programming, vectors are a fundamental data structure.

Here's a detailed guide on


creating and naming vectors, performing vector arithmetic, and sub-setting vectors in R.
You can create vectors in R using the c() function, which stands for "combine.“
EXAMPLE:

numeric_vector <- c(1, 2, 3, 4, 5)


char_vector <- c("apple", "banana", "cherry")
logical_vector <- c(TRUE, FALSE, TRUE)
2. Naming Vectors
You can assign names to each element in a vector to make them easier to
reference.
Assigning names during the creation:
named_vector <- c(a = 1, b = 2, c = 3)
Assigning names after creation:
vector <- c(1, 2, 3)
names(vector) <- c("a", "b", "c")
3. Vector Arithmetic
In R, you can perform arithmetic operations on vectors, and these operations
are applied element-wise.
Addition:
v1 <- c(1, 2, 3) , v2 <- c(4, 5, 6) , v3 <- v1 + v2 # Result: c(5, 7, 9)
Subtraction:
v4 <- v2 - v1 # Result: c(3, 3, 3)
Multiplication:
v5 <- v1 * v2 # Result: c(4, 10, 18)
Division:
v6 <- v2 / v1 # Result: c(4, 2.5, 2)
4. Vector Subsetting
Subsetting vectors in R allows you to extract specific elements.
Extracting a Single Element:
vector <- c(10, 20, 30, 40, 50)
second_element <- vector[2] # Result: 20
Extracting Multiple Elements:
subset <- vector[c(1, 3, 5)] # Result: c(10, 30, 50)
Subsetting using logical Conditions:
logical_subset <- vector[vector > 30] # Result: c(40, 50)
Subsetting with Named Vectors:
named_vector <- c(a = 10, b = 20, c = 30)
subset_named <- named_vector["b"] # Result: 20
• R-matrix is a two-dimensional arrangement of data in rows and
columns.
• In a matrix, rows are the ones that run horizontally and columns are the
ones that run vertically.
• In R programming, matrices are two-dimensional, homogeneous data
structures. These are some examples of matrices:
To create a matrix in R you need to use the function called matrix().
• The arguments to this matrix() are the set of elements in the vector. You
have to pass how many numbers of rows and how many numbers of
columns you want to have in your matrix.
Syntax:
matrix(data, nrow, ncol, byrow, dimnames)
Parameters:
data – values you want to enter
nrow – no. of rows
ncol – no. of columns
byrow – logical clue, if ‘true’ value will be assigned by rows
dimnames – names of rows and columns
• A diagonal matrix is a matrix in which the entries outside the main
diagonal are all zero. To create such a R matrix the syntax is given below:
• An identity matrix in which all the elements of the principal diagonal are
ones and all other elements are zeros. To create such a R matrix the syntax
is given below
R – subsetting
Method 1: Subsetting in R Using [ ] Operator
Using the ‘[ ]’ operator, elements of vectors and observations from data frames can be
accessed. To neglect some indexes, ‘-‘ is used to access all other indexes of vector or data
frame.
# Create vector
x <- 1:15

# Print vector
cat("Original vector: ", x, "\n")

# Subsetting vector
cat("First 5 values of vector: ", x[1:5], "\n")

cat("Without values present at index 1, 2 and 3: ", x[-c(1, 2, 3)], "\n")


Original vector: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
First 5 values of vector: 1 2 3 4 5
Without values present at index 1, 2 and 3: 4 5 6 7 8 9 10 11 12 13 14 15
Method 2: Subsetting in R Using [[ ]] Operator
[[ ]] operator is used for subsetting of list-objects. This operator is the same
as [ ] operator but the only difference is that [[ ]] selects only one element
whereas [ ] operator can select more than 1 element in a single command.
# Create list
ls <- list(a = 1, b = 2, c = 10, d = 20)

# Print list
cat("Original List: \n")
print(ls)

# Select first element of list


cat("First element of list: ", ls[[1]], "\n")
• Original List:
• $a
• [1] 1

• $b
• [1] 2

• $c
• [1] 10

• $d
• [1] 20

• First element of list: 1


# Create list
z <- list(a = list(x = 1, y = "GFG"), b = 1:10)

# Print list
cat("Original list:\n")
print(z)

# Print GFG using c() function


cat("Using c() function:\n")
print(z[[c(1, 2)]])

# Print GFG using only [[]] operator


cat("Using [[]] operator:\n")
print(z[[1]][[2]])
• Original list:
• $a
• $a$x
• [1] 1

• $a$y
• [1] "GFG"

• $b
• [1] 1 2 3 4 5 6 7 8 9 10

• Using c() function:


• [1] "GFG"

• Using [[]] operator:


• [1] "GFG"
Method 3: Subsetting in R Using $ Operator
$ operator can be used for lists and data frames in R. Unlike [ ] operator, it selects only a
single observation at a time. It can be used to access an element in named list or a column
in data frame. $ operator is only applicable for recursive objects or list-like objects.
# Create list
ls <- list(a = 1, b = 2, c = "Hello", d = "GFG")

# Print list
cat("Original list:\n")
print(ls)

# Print "GFG" using $ operator


cat("Using $ operator:\n")
print(ls$d)
Original list:
$a
[1] 1

$b
[1] 2

$c
[1] "Hello"

$d
[1] "GFG"

Using $ operator:
[1] "GFG"
Method 4: Subsetting in R Using subset() Function
subset() function in R programming is used to create a subset of vectors,
matrices, or data frames based on the conditions provided in the
parameters.
Syntax: subset(x, subset, select)
Parameters:
• x: indicates the object
• subset: indicates the logical expression on the basis of which subsetting
has to be done
• select: indicates columns to select
Subsetting
airq <- subset(airquality, Temp < 65, select = c(Month))
Print subset
print(airq)
# Subsetting
mtc <- subset(mtcars, gear == 5 & hp > 200, select = c(gear, hp))

# Print subset
print(mtc)
• In R, an array is a data structure that holds elements in multiple dimensions.
• Arrays in R can be one-dimensional (vectors), two-dimensional (matrices), or higher-
dimensional
Creating Arrays
To create an array in R, you use the array() function. This function takes a vector of data
and a dim attribute that defines the dimensions of the array
# Create two vectors
vector1 <- c(5, 10, 15, 20)
vector2 <- c(25, 30, 35, 40, 45, 50, 55, 60)
# Combine vectors into an array with specified dimensions
final_array <- array(c(vector1, vector2), dim = c(4, 4, 2))
print(final_array)
• ,1

• [,1] [,2] [,3] [,4]


• [1,] 5 25 45 5
• [2,] 10 30 50 10
• [3,] 15 35 55 15
• [4,] 20 40 60 20

• ,,2

• [,1] [,2] [,3] [,4]


• [1,] 25 45 5 25
• [2,] 30 50 10 30
• [3,] 35 55 15 35
• [4,] 40 60 20 40
Indexing Arrays
You can access elements of an array using indices for each dimension. The indexing is
similar to matrices where you specify rows and columns using array[row, column] syntax
# Accessing a specific element from the array
element <- final_array[1, 3, 1]
print(element) # Should print the element at first row, third column of the first matrix
Adding Elements to Arrays

Elements can be added to arrays in R using functions like c() and append(). The new
elements are added at the end or at a specified position within the array
Example:
# Original vector
original_vector <- c(1, 2, 3)

# Adding an element to the end of the vector


new_vector <- c(original_vector, 4)
print(new_vector) # Should print "1 2 3 4"
Removing Elements from Arrays
You can remove elements from an array by subsetting the array and excluding the
elements you want to remove
Example:
# Removing element '3' from the vector
filtered_vector <- original_vector[original_vector != 3]
print(filtered_vector) # Should print "1 2"
In R programming, Class R refers to the classification system for objects and
their associated classes. An object in R is a collection of data and functions,
while a class acts as a blueprint for the object, defining its structure and
behavior
S3, S4, and Reference Classes
R has three systems for classes: S3, S4, and Reference classes. S3 is the most
commonly used system in R, where objects are created by setting the class
attribute. S4 classes offer a more formal definition with setClass(), and
Reference classes are similar to object-oriented programming in other
languages, using setRefClass() for definition
Here's how you can create an S3 class in R:
# Create a list with required components
student1 <- list(name = "John", age = 21, GPA = 3.5)

# Name the class appropriately


class(student1) <- "Student_Info"

# Create and call an object


Student1
This example demonstrates creating a list with various components and
assigning it a class using the class() function. The resulting object student1
is an instance of the "Student_Info" class
For a Reference class, you would define it using setRefClass():
# Define a reference class
Student_Info <- setRefClass("Student_Info",fields=list(name="character", age="numeric",
GPA="numeric"))

# Use the generator function to create an object


student1 <- Student_Info(name = "John", age = 21, GPA = 3.5)

# Call the object


student1
This code snippet shows how to define and instantiate a Reference class in R. The generator
function Student_Info() is used to create new objects of this class
Understanding these concepts is crucial for effective programming in R, especially when
dealing with complex data structures or developing packages.
Example of Creating an S4 Class
To create an S4 class, you would use the setClass() function like this:
# Define a class with slots
setClass("Student_Info", slots=list(name="character", age="numeric", GPA="numeric"))

# Create an object of the class


student1 <- new("Student_Info", name = "John", age = 21, GPA = 3.5)

# Call the object


Student1

In this example, setClass() is used to define the structure of the "Student_Info" class, and new() creates an object
of that class

You might also like