What is a matrix in R?
A matrix is, in most cases, a two-dimensional atomic data structure (although we can have a one-dimensional matrix, or a non-atomic matrix made from a list).
How can we create a matrix?
To create a matrix, we can use the matrix() function on a vector with the nrow and/or ncol arguments:
x <- matrix(1:20, nrow = 5)
The above code will produce a matrix with five rows and four columns containing the numbers 1 through 20. The matrix will be filled by column unless the argument byrow is set to TRUE
How can we create a matrix from a vector?
To create a matrix, we can use the matrix() function on a vector with the nrow and/or ncol arguments:
x <- matrix(1:20, nrow = 5)
The above code will produce a matrix with five rows and four columns containing the numbers 1 through 20. The matrix will be filled by column unless the argument byrow is set to TRUE
Why do R always print the position indexes for matrixes?
It just does, so that we can use that information. Since a matrix is naturally two-dimensional, R provides column indexes to more easily interact with the matrix.
How can we access the value of an individual cell inside a matrix?
We can use the index vector [] to return the value of an individual cell of the matrix. For example:
x[1,2]
will return the value of row 1, column 2.
How can we manipulate a matrix?
We can use the index vector [] to return the value of an individual cell of the matrix. For example:
x[1,2]
will return the value of row 1, column 2. We can also change the value inside a cell of a matrix:
x[1,2] <- 5
How can we select all values from a matrix that are greater than 5?
matrix1[matrix1 > 5]
The statement above uses what is called a Boolean operator. Basically a Boolean operator uses true/false statements to decide which data to select. In this case, we asked R to give us all the values of matrix1 which had values greater than 5, and it returned these values as a mathematical vector. We could also have asked for values less than, equal to, greater than or equal to, less than or equal to, or not equal to using, ―<―, ―==―, ―>=―, ―<=―, and ―!=―, respectively.
A simpler use of Boolean operators can be seen by using the command below:
> matrix1 > 5
As you can see, R has returned the matrix as a matrix of true and false values instead of numbers, where the true or false tells you whether that element satisfied the Boolean operation ―> 5‖. When you asked for ―matrix1[matrix1 > 5] R internally created this matrix of true/false values and then returned to you only the values that were true.
How can we get the values of a specific rows or column inside a matrix?
We can also use the index vector to return the values of whole rows or column:
x[1,]
How can we create a matrix by assigning dimensions to a vector using the dim() function?
x <- 1:20
dim(x) <- c(5,4)
Can we redefine the dimensions of a matrix?
Yes. For example:
dim(x) <- c(4,5)
will "redraw" the matrix to have four rows and five columns.