Week 4
Aim:
☛ Write R command to
i) Illustrates the usage of Vector subsetting and Matrix subsetting
ii) Write a program to create an array of 3 X 3 matrixes with 3 rows and 3 columns.
Solution :
i) Illustrates the usage of Vector subsetting and Matrix subsetting .
Vector Subsetting in R :
Program:
> # Define a vector
> vec <- c(10, 20, 30, 40, 50)
> # Subset by position
> print(vec[1]) # First element
[1] 10
> print(vec[2:4]) # Elements from position 2 to 4
[1] 20 30 40
> # Subset by negative index (exclude elements)
> print(vec[-1]) # All except the first element
[1] 20 30 40 50
> print(vec[-(2:3)]) # Exclude 2nd and 3rd elements
[1] 10 40 50
> # Subset by logical vector
> print(vec[c(TRUE, FALSE, TRUE, FALSE, TRUE)]) # Select 1st, 3rd, and 5th
[1] 10 30 50
> # Subset by condition
> print(vec[vec > 25]) # Elements greater than 25
[1] 30 40 50
Matrix Subsetting in R :
Program:
> # Define a matrix
> mat <- matrix(1:9, nrow = 3, byrow = TRUE)
> # mat =
> # [,1] [,2] [,3]
> # [1,] 1 2 3
> # [2,] 4 5 6
> # [3,] 7 8 9
> # Subset by element
> mat[1, 2] # Element at 1st row, 2nd column
[1] 2
> # Subset entire row or column
> mat[2, ] # Entire 2nd row
[1] 4 5 6
> mat[, 3] # Entire 3rd column
[1] 3 6 9
> # Subset a submatrix
> mat[1:2, 2:3] # Rows 1-2, Columns 2-3
[,1] [,2]
[1,] 2 3
[2,] 5 6
> # Subset with condition
> mat[mat > 5] # All elements > 5 (returns as a vector)
[1] 7 8 6 9
> # Subset with drop = FALSE to preserve matrix structure
> mat[1, , drop = FALSE] # 1st row as a matrix
[,1] [,2] [,3]
[1,] 1 2 3
ii) Write a program to create an array of 3ร3 matrixes with 3 rows and 3 columns.
Program:
Filename: ArrayMatrix.R
# Create an array of 3x3 matrices (3 rows, 3 columns, 2 layers)
my_array <- array(1:18, dim = c(3, 3, 2))
# Print the array
print("Array of 3x3 matrices (2 layers):")
print(my_array)
# Access individual matrix (layer)
print("First 3x3 matrix:")
print(my_array[,,1])
print("Second 3x3 matrix:")
print(my_array[,,2])
Output:
[1] "Array of 3x3 matrices (2 layers):"
, , 1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
, , 2
[,1] [,2] [,3]
[1,] 10 13 16
[2,] 11 14 17
[3,] 12 15 18
[1] "First 3x3 matrix:"
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
[1] "Second 3x3 matrix:"
[,1] [,2] [,3]
[1,] 10 13 16
[2,] 11 14 17
[3,] 12 15 18
๐ป Run This R Program
Week 4
The selected R program is loaded
automatically into the editor.
Edit the program, provide input if required
and click Run.
The compiler is embedded using OneCompiler.
Your R program runs inside the embedded R environment;
Study Glance does not execute R code directly on your web
server. Programs that draw charts (pie, bar, box plots,
histograms), read a CSV file from your own computer or
install packages may not behave the same way in an online
sandbox. Run those in RStudio or the R console.