๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Matrices

A matrix holds values of one type in rows and columns. It is a grid where every row has the same number of cells.

Fill down the columns

The values one to six fill a grid with two rows. They run down the first column before they move to the next one.

m <- matrix(1:6, nrow = 2)
print(m)

Fill across the rows

byrow set to TRUE changes the fill direction. The values now run across the first row before they drop to the second one.

m <- matrix(1:6, nrow = 2, byrow = TRUE)
print(m)

Read one cell

The brackets hold a row number and a column number. They pick the cell in row two and column one.

m <- matrix(1:6, nrow = 2)
print(m[2, 1])

Sums and size

colSums adds each column and rowSums adds each row. nrow and ncol then report two rows and three columns.

m <- matrix(1:6, nrow = 2)
print(colSums(m))
print(rowSums(m))
print(nrow(m))
print(ncol(m))

Example

grid <- matrix(c(4, 8, 2, 6), nrow = 2, byrow = TRUE)
print(grid)
print(rowSums(grid))

Key points

  • matrix() builds a matrix from a vector of values.
  • Values fill down each column first by default.
  • byrow = TRUE fills values across each row instead.
  • One cell is read with its row and column inside brackets.
  • colSums() adds each column and rowSums() adds each row.
  • nrow() counts the rows and ncol() counts the columns.

In this example, byrow fills the grid across the rows. rowSums then reports 12 for the first row and 8 for the second row.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

How does matrix(1:6, nrow = 2) place the value 2?