# Beyond Vectors: Introduction to Matrices and Arrays in R

Vectors, matrices, arrays, what is the difference? The difference has to do with the number of dimensions that they have. A vector is only only one dimension. Vectors are one row of information. Matrices have two dimensions which are rows and columns. Any Microsoft excel spreadsheet is a matrix of rows and columns and thus contains two dimensions. An array is anything with three or more dimensions such as height, width and depth. Anything beyond three dimensions is hard for the typical mind to grasp.

Creating a Matrix

We will now create a simply matrix below. An explanation is provided after the code

```> matrix.1 <- matrix(1:20, ncol=4)
> matrix.1
[,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20```

Here is what we did

1. We created the variable ‘matrix.1’
2. Within this variable we put a matrix that contain the numbers 1 to 20 (1:20)
3. When the specified that we want four columns.
4. R creates the matrix
5. We type ‘matrix.1’ into R and press enter so we can see the matrix

Once you specify the number of columns R determines the number of rows itself. However, R does not like empty space in the rows and columns. Therefore, you matrix must use all of the space possible within it or you will get the message below.

```> matrix.1 <- matrix(1:19, ncol=4)
Warning message:
In matrix(1:19, ncol = 4) :
data length  is not a sub-multiple or multiple of the number of rows ```

In the example above, I tried to put 19 numbers into a matrix that had 4 columns and 5 rows which equals 20 spaces or indices. Since there was one empty space R did not want to create the matrix.

Examining the Properties of Matrices

If you type in the function “str” you get the following information

```> str(matrix.1)
int [1:5, 1:4] 1 2 3 4 5 6 7 8 9 10 ...```

Here is what this information means

• int means that the matrix contains integers
• 1:5 means that there are 5 rows and all rows are included in this description
• 1:4 means that there are 4 columns and all columns are included in this description
• 1 2 3 4 5 6 7 8 9 10 … is just the first ten indices in the matrix

The “dim” function will tell you the dimensions of the matrix and the “length” function tells you how many indices there are in the matrix. Both are below.

```> dim(matrix.1)
 5 4
> length(matrix.1)
 20```

The “dim” function indicates we have 5 rows and 4 columns. The ‘length’ function indicates that we have 20 indices.

This serves only as in introduction to matrices. We haven’t really dealt with arrays yet but many of the same ideas and concepts apply equally to them as well.