2. Objects that contain a matrix


Objects can also store series of data arranged in the form of a two-dimensional matrix, i.e. an arrangement of data in rows and columns. The function matrix() creates this type of object, but requires a few arguments to properly “draw” the matrix and dispatch the data. First, let’s agree that the matrix will be called my.first.matrix and will contain 20 entries, which will be display in 5 columns and 4 rows. Let’s put the entries into a vector named entries (for simplicity, the entries will be values ranging from 1 to 20, in a logical order; this can be written 1:20). Then, we write the function my.first.matrix <- matrix(entries, nrow=4, ncol=5):

[code language=”r”]
entries <- 1:20
entries

my.first.matrix <- matrix(entries, nrow=4, ncol=5)

my.first.matrix
[/code]

matrix

As you see in the picture above, our first matrix has been created and the data ranging from 1 to 20 are now dispatched column by column, starting with the left column and from the top, and following in the next column… if you originally meant to dispatch the data row by row, starting from the top and from the left side, you need to add the argument byrow=TRUE in the matrix function:

[code language=”r”]
my.first.matrix <- matrix(entries, nrow=4, ncol=5, byrow=TRUE)

my.first.matrix
[/code]

 matrix byrow

You may have noticed that your matrix is surrounded with reference number/marks between brackets and following or followed by a comma. These indicate the number of the rows and columns. This not only makes it easier to visually find coordinates and positions in large matrices, but also allows you to quickly extract data from the matrix. Let’s take an example. In my.first.matrix, you wish to retrieve the value placed where the 3rd row and the 4th column meet. Simple type my.first.matrix[3,4] and R returns the value “14”. If you omit the number of the column or the row, R returns the whole row or the whole column, respectively. The following picture illustrates this example:

[code language=”r”]
my.first.matrix[3,4]
my.first.matrix[3,]
my.first.matrix[,4]
[/code]

matrix coordinates

  Fant du det du lette etter? Did you find this helpful?
[Average: 0]