Matrix in R is constructed using
So here's what happened above, first the data was concatenated using the
Notice the names of the rows are retained in the output? To get rid of this, try
What about the
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.
matrix
function, we can code this as
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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 datanrow
- the number of rowsncol
- the number of columnsbyrow
- the orientation of how data is wrapped into a matrix. IfTRUE
, then it's row-wise, otherwise, column-wise.
rbind
for the same data, this is how you do it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
cbind
function?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |