How to Create Empty Matrix in R

An empty matrix can be created simultaneously as we create a regular matrix in R, but we will not provide any value inside the matrix function.

How to create an empty Matrix in R

To create an empty matrix in R, use the matrix() function, do not pass any data; pass ncol = 0 values and pass the nrow value to whatever you like.

mtrx <- matrix(, nrow = 5, ncol = 0)
print(mtrx)

Output

[1,]
[2,]
[3,]
[4,]
[5,]

In R, one column is created by default for a matrix; therefore, to create a matrix without a column, we have used ncol =0. You can also create an empty matrix in R using the matrix() function and do not pass any data but pass the nrow and ncol parameters.

mtrx <- matrix(, nrow = 5, ncol = 5)
print(mtrx)

Output

     [,1] [,2] [,3] [,4] [,5]
[1,]  NA   NA   NA   NA   NA
[2,]  NA   NA   NA   NA   NA
[3,]  NA   NA   NA   NA   NA
[4,]  NA   NA   NA   NA   NA
[5,]  NA.  NA   NA   NA   NA

And we got the 5 x 5 matrix filled with NA values. The above matrix is filled with Not Available values, and from now, you can add values to the empty matrix.

If you don’t know the number of columns ahead of time, add each column to a list and cbind() at the end.

list <- list()
for (i in 1:5) {
 row_val <- NA
 list[[i]] <- row_val
}
mtrx <- do.call(cbind, list)
mtrx

Output

      [,1] [,2]  [,3]  [,4]  [,5]
[1,]  NA    NA    NA    NA    NA

 Creating Matrix with Zero Rows in R

To create a matrix with zero rows in R, pass the nrow = 0 to the matrix() function.

mtrx <- matrix(ncol = 4, nrow = 0)
mtrx

Output

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

That is it for this tutorial.

Related posts

How to create an empty list in R

How to create an empty vector in R

How to create an empty data frame in R

Leave a Comment