Home » How to Create an Empty Matrix in R (With Examples)

How to Create an Empty Matrix in R (With Examples)

by Erma Khan

You can use the following syntax to create an empty matrix of a specific size in R:

#create empty matrix with 10 rows and 3 columns
empty_matrix 10, ncol=3)

The following examples show how to use this syntax in practice.

Example 1: Create Empty Matrix of Specific Size

The following code shows how to create an empty matrix of a specific size in R:

#create empty matrix with 10 rows and 3 columns
empty_matrix 10, ncol=3)

#view empty matrix
empty_matrix

      [,1] [,2] [,3]
 [1,]   NA   NA   NA
 [2,]   NA   NA   NA
 [3,]   NA   NA   NA
 [4,]   NA   NA   NA
 [5,]   NA   NA   NA
 [6,]   NA   NA   NA
 [7,]   NA   NA   NA
 [8,]   NA   NA   NA
 [9,]   NA   NA   NA
[10,]   NA   NA   NA

#view class
class(empty_matrix)

[1] "matrix" "array" 

The result is a matrix with 10 rows and 3 columns in which every element in the matrix is blank.

Example 2: Create Matrix of Unknown Size

If you don’t know what the final size of the matrix will be ahead of time, you can use the following code to generate the data for the columns of the matrix and bind each column together using the cbind() function:

#create empty list
my_list #add data using for loop
for(i in 1:4) {
    my_list[[i]] #column bind values into a matrix
my_matrix = do.call(cbind, my_list)

#view final matrix
my_matrix

            [,1]        [,2]       [,3]       [,4]
 [1,]  1.3064332  1.18175760  2.1603867  1.2378847
 [2,]  0.8618439  0.66663694  0.1113606  0.2062029
 [3,] -0.4689356 -0.03200797 -1.3872632  1.6531437
 [4,] -0.4664767 -0.79285400  0.3972758  0.1632975
 [5,]  0.5880580  1.05795303 -0.5655543 -0.3557376
 [6,]  0.5412100 -0.32070294 -0.3687303 -1.1778959
 [7,]  0.5073627 -0.24925226  1.0031305  0.6336998
 [8,]  0.8047177  0.10968558  0.3225197  1.6776955
 [9,]  1.5755134  1.40435730  1.8360239  0.5612274
[10,] -0.6430913  0.01173386  0.3181037 -0.8414270

The result is a matrix with 10 rows and 4 columns.

Additional Resources

The following examples show how to create other empty objects in R:

How to Create an Empty Data Frame in R
How to Create an Empty List in R
How to Create an Empty Vector in R

Related Posts