Select Page
24 Shares

In this short tutorial, you will learn how to create a matrix in R. We will use the `matrix()` function, among two other functions, for this aim. Specifically, we will go into the details of this function as this will enable us to e.g. name the columns and rows in the matrix we create. That is, we will look at the different arguments of the `matrix()` function in R. In the next section, you will find the outline of the tutorial.

## Outline

As previously mentioned, this post will cover the creation of a matrix in R by examples. In the first section, however, we will look at the different arguments of the `matrix()` function (the function we will use to create matrices). In the second section, we will answer the questions “what is a matrix in R?” and  “how to create a matrix in R?”

After these two questions (and answers) we will continue with the first example on how to create a matrix in R. Here we will use the `matrix()` function when creating a matrix in R. In the second example, we will have a look at how we can use the `rbind()` function to combine a couple of vectors into a matrix. After this, we will use the `cbind()` to accomplish the same (but with a different result) and, then, the `rbind()` function. In these two examples, we will see how to create a matrix from vectors in R. The 5th example will show you have to create an empty matrix and the last how to name the rows and columns. In the 6th and final example, you will learn how to create a matrix of zeros in R.

## What is a matrix in R?

In R, a matrix is a collection of elements of the same data type such as numeric, character, or logical). Moreover, these elements are arranged into a fixed number of rows and columns (e.g., 3 rows and 3 columns, 10 rows, and 2 columns). This type of data is 2-dimensional.

## How to create a matrix in R?

A matrix can be created in R using the matrix() function. For example, the following code will produce a 3 by 3 matrix: `mtx <- matrix(3:11, nrow = 3, ncol = 3)`. Moreover, it is possible to combine vectors to create a matrix.

In the next section, you will get an overview of the `matrix()` function.

## Syntax of the Matrix() Function

Here’s the general syntax of the matrix function:

```.wp-block-code {
border: 0;
}

.wp-block-code > span {
display: block;
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,
dimnames = NULL)```Code language: PHP (php)```

As you can see, there are five parameters that you can use:

• data – this argument is optional and will contain e.g. a vector of your data (see the previous section or the following examples).
• nrow – this argument is used to get the number of rows, you want (see the coming examples)
• ncol – this argument is, like nrow, but for the number of columns you want in your created matrix
• dimnames – this argument is used if you want to name the columns and rows (see the last example in the post)

In the next section, we will create our first matrix in R.

## How to Create a Matrix in R – Example 1

Here’s the first example of how to create a matrix:

``````mtx <- matrix(seq(1,9),
nrow = 3,
ncol = 3)```Code language: HTML, XML (xml)```

As you can see, in the code chunk above, we used the seq() function to create a sequence in R (i.e., a vector). Moreover, we used the `nrow` and `ncol` arguments to tell the matrix() function that we want to create a three by three matrix. Here’s how the matrix, called `mtx`, look like:

In the next example, we will have a look at how to make a matrix and set the `byrow` argument to `TRUE`.

## Example 2: Create a Matrix in R by rows

Here’s how we can create a matrix in R from a sequence of numbers (i.e., a vector) and get the numbers by rows:

``````mtx <- matrix(seq(1,9),
nrow = 3,
ncol = 3,
byrow = TRUE)```Code language: R (r)```

Note that we can flip the order by transposing the matrix in R using the `t()` function (i.e., by typing `t(mtx)`).  This would result in a matrix exactly like the one in the first example. Here’s a post for more information about transposing in R:

In the following example, we will look at merging three vectors into a matrix. See also the recent post on how to remove a row in R (from matrix and dataframe).

## Example 3: Create a Matrix from vectors in R using the cbind() Function

Here’s how to use the `cbind()` function to produce a matrix in R:

``````mtx <- cbind(seq(1,3), seq(4, 6),
seq(7, 9))``````

Note, this method may be more feasible when we happen to have data stored in vectors already. Here’s the created matrix:

As you can see in the image above, we get the exact same result as in the first example. In the next example, before returning to using the `matrix()` function, we will have a look at

## Example 4: Create a Matrix from vectors in R using the rbind() Function

Here’s how to use the `rbind()` function to make a matrix from vectors in R:

``````mtx <- rbind(seq(1,3), seq(4, 6),
seq(7, 9))``````

As with the `cbind()` method for creating a matrix it might be more useful to create matrices this way when we have data in vectors, to begin with. Here’s the created matrix:

Again, this method created the exact same matrix as in example 2. In the next example, we will look at how we can create an empty matrix in R.

## Example 5: How to Create an Empty Matrix in R

Here’s how we can create an empty matrix in R:

``empty_matrix <- matrix(nrow = 4, ncol = 4)`Code language: HTML, XML (xml)`

As you can see, we skipped the first argument (i.e., data) this time. However, we did create an empty 4 by 4 matrix, and here’s the result:

It is now possible to fill this empty matrix with data (i.e., calculations). In the next example, we will look at how we can name the rows and columns when creating the matrix.

## Example 6: How to Name the Rows and Columns when Creating a Matrix in R

Now, to name the rows and columns when creating a matrix we use the `dimnames` argument:

``````mtx <- matrix(seq(1,9),
nrow = 3,
ncol = 3,
dimnames = list(c("1", "2" ,"3"),
c("Vector", "List", "Matrix")))```Code language: PHP (php)```

In the code chunk above, we named the rows something straightforward: 1, 2, and 3. Just for fun, we called the columns “Vector”, “List”, and “Matrix”.

In the next, and final example, you will learn how to generate a matrix of zeros in R.

## Example 7: How to Create a Matrix of Zeros in R

Here’s how we can create a matrix of zeros in R:

``````mtx_zeros <- matrix(rep(0, 9),
ncol = 3,
nrow = 3)```Code language: R (r)```

In the code chunk above, we used the rep() function in R to repeat the number zero 9 times. This enabled us to generate a matrix populated by zeros. Here’s the result:

For more information, see the documentation of the different functions used in this tutorial:

Now that you have your data in your matrix you can calculate the five-number summary in R, create a violin plot in R, or make a scatter plot in r, for example. Moreover, you can also convert the matrix to a data frame.

## Summary

This post taught you how to create a matrix in R. More specifically, you have learned by six examples. First, we had a quick look at the `matrix()` function and its syntax. Second, we answered some questions. Additionally, you have learned how to make a matrix by the examples. First, we just created a 3 x 3 matrix using a sequence of numbers and the `nrow` and `ncol` arguments. Second, we used the `byrow` argument to get a slightly different matrix. In the third and fourth examples, we used the `cbind()` and `rbind()` functions, respectively. This was followed by learning how to create an empty matrix in R and how to name the columns and rows when creating the matrix. I hope you learned something. If you did, please share the post on your social media accounts and leave a comment below. Additionally, if there is something you want to be covered on the blog, leave a comment or contact me.

Here are some other blog posts that you may find useful:

24 Shares