Practical Lab Session: Vector, Matrix, Array, Data Frame, and List in R
1) Vector (1D Structure)
Definition: A vector is a one-dimensional structure that stores elements of the same data
type.
Program:
v1 <- c(10, 20, 30, 40, 50)
mean(v1)
Output:
[1] 10 20 30 40 50
[1] 30
Comment: Vectors store same data type. They are the basic building block in R.
2) Matrix (2D Structure)
Definition: A matrix is a two-dimensional structure with rows and columns. All elements
must be the same data type.
Program:
m1 <- matrix(c(1,2,3,4,5,6), nrow=2, byrow=TRUE)
m1
sum(m1)
Output:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[1] 21
Comment: Matrix is useful for mathematical operations and linear algebra.
3) Array (Multi-Dimensional)
Definition: An array can have more than two dimensions. Matrix is a special case of array.
Program:
arr1 <- array(1:8, dim=c(2,2,2))
arr1
Output:
,,1
[,1] [,2]
[1,] 1 3
[2,] 2 4
,,2
[,1] [,2]
[1,] 5 7
[2,] 6 8
Comment: Arrays are used in simulations and multi-dimensional data analysis.
4) Data Frame (Tabular Data)
Definition: A data frame is a table where columns can have different data types.
Program:
df1 <- [Link](
Name=c("Ali","Sara","John"),
Age=c(20,22,21),
Grade=c("A","B","A")
df1
Output:
Name Age Grade
1 Ali 20 A
2 Sara 22 B
3 John 21 A
Comment: Data frame is mainly used in data analysis and machine learning.
5) List (Flexible Structure)
Definition: A list can store different data types and structures.
Program:
list1 <- list(
numbers=c(1,2,3),
matrix=matrix(1:4,nrow=2),
text="Hello"
list1
Output:
$numbers
[1] 1 2 3
$matrix
[,1] [,2]
[1,] 1 3
[2,] 2 4
$text
[1] "Hello"
Comment: Lists are used to store complex outputs like model results.