r22 Unit3 Vector Matrix
r22 Unit3 Vector Matrix
# Print vector
cat("Original vector: ", x, "\n")
# Subsetting vector
cat("First 5 values of vector: ", x[1:5], "\n")
# Print list
cat("Original List: \n")
print(ls)
• $b
• [1] 2
• $c
• [1] 10
• $d
• [1] 20
# Print list
cat("Original list:\n")
print(z)
• $a$y
• [1] "GFG"
• $b
• [1] 1 2 3 4 5 6 7 8 9 10
# Print list
cat("Original list:\n")
print(ls)
$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
• ,,2
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)
In this example, setClass() is used to define the structure of the "Student_Info" class, and new() creates an object
of that class