Loading web-font TeX/Main/Regular
Skip to main content

R: Enter Data in Matrix Format

Matrix in R is constructed using matrix, rbind, or cbind function. These functions have the following descriptions:
  • matrix - used to transform a concatenated data into matrix, of compatible dimensions;
  • rbind - short for row bind, that binds a concatenated data points of same sizes by row;
  • cbind - short for column bind, that binds a concatenated data points of same sizes by column.
Example 1. Consider this matrix, \left[\begin{array}{ccc} 3&4&5\\ 2&1&3\\ 6&5&4 \end{array}\right]. Using the matrix function, we can code this as

data.a <- c(3,4,5,2,1,3,6,5,4)
matrix.a <- matrix(data.a, nrow = 3, ncol = 3, byrow = TRUE)
matrix.a
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 2 1 3
[3,] 6 5 4
view raw Matrixa.R hosted with ❤ by GitHub
So here's what happened above, first the data was concatenated using the c function into a data.a object. Next, we transformed this into a matrix of compatible dimension, that is 3\times 3. Below are the description of the arguments:
  • data.a - the data
  • nrow - the number of rows
  • ncol - the number of columns
  • byrow - the orientation of how data is wrapped into a matrix. If TRUE, then it's row-wise, otherwise, column-wise.
Let's try the rbind for the same data, this is how you do it

row1 <- c(3,4,5)
row2 <- c(2,1,3)
row3 <- c(6,5,4)
matrix.b <- rbind(row1, row2, row3)
matrix.b
[,1] [,2] [,3]
row1 3 4 5
row2 2 1 3
row3 6 5 4
view raw Matrix1.R hosted with ❤ by GitHub
Notice the names of the rows are retained in the output? To get rid of this, try

matrix.c <- rbind(c(3,4,5), c(2,1,3), c(6,5,4))
matrix.c
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 2 1 3
[3,] 6 5 4
view raw Matrix2.R hosted with ❤ by GitHub
What about the cbind function?

matrix.d <- cbind(c(3,2,6),c(4,1,5),c(5,3,4))
matrix.d
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 2 1 3
[3,] 6 5 4
view raw Matrix3.R hosted with ❤ by GitHub