In R, vectors can be integer, double, character, logical, complex and raw types. A vector is created using the c() function:
a <- c(val1, val2, ...
Creating a List of Vectors
A list of vectors in R is an array of more than one vector kept in a list structure. Creating a list of vectors is done in the following way:
a <- list() # Create an empty list 'a'
i <- 1 # Initialize i to 1
j <- 4 # Initialize j to 4
# Loop to create 5 vectors and store them in the list
for (k in 1:5) {
a[[k]] <- c(i:j)
i <- i + 1
j <- j + 1
}
print("The list of vectors is: ")
print(a)
Output
[1] "The list of vectors is: " [[1]] [1] 1 2 3 4 [[2]] [1] 2 3 4 5 [[3]] [1] 3 4 5 6 [[4]] [1] 4 5 6 7 [[5]] [1] 5 6 7 8
Matrix from List of Vectors
Matrices in R can be formed from a list of vectors with the help of functions such as do.call() and matrix().
Using do.call() Function
do.call() helps you execute a function (such as rbind()) on a list of arguments. Here's how to use it to form a matrix:
do.call(rbind, a)
Output:
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 2 3 4 5
[3,] 3 4 5 6
[4,] 4 5 6 7
[5,] 5 6 7 8
we call the do.call() function and pass the arguments as rbind and a.
Using matrix() Function
The matrix() function is used to transform a list of vectors into a matrix. To accomplish this, we first transform the list into a single vector with unlist(), then form the matrix:
Syntax:
matrix(data, nrow, ncol, byrow, dimnames)
Where,
- data: is the input vector which represents the elements in the matrix
- nrow: specifies the number of rows to be created
- ncol: specifies the number of columns to be created
- byrow: specifies logical value. If TRUE, matrix will be filled by row. Default value is FALSE.
- dimnames: specifies the names of rows and columns
ug<-list()
i<-1
j<-5
# Create list of vectors
for (k in 1:6){
ug[[k]]<-c(i:j)
i<-i+1
j<-j+1
}
# Convert list to a matrix
matrix(unlist(ug), byrow=TRUE, nrow=length(ug) )
Output
[,1] [,2] [,3] [,4] [,5] [1,] 1 2 3 4 5 [2,] 2 3 4 5 6 [3,] 3 4 5 6 7 [4,] 4 5 6 7 8 [5,] 5 6 7 8 9 [6,] 6 7 8 ...