A B C D
a 1 7 13 19
b 2 8 14 20
c 3 9 15 21
d 4 10 16 22
e 5 11 17 23
f 6 12 18 24
(Sections 7.1 - 7.3)
R was designed for statistics and data analysis. It supports data structures that make data analysis easier.
In this Chapter we learn about one such data structure: data frames.
Unlike the vectors you have met so far, data frames are two-dimensional.
So, as a warm-up, we look at another two-dimensional data structure in R: the matrix.
Matrix
An atomic vector that has two additional attributes: a number of rows and a number of columns.
Take a vector and give it those two extra attributes, using the matrix() function.:
You could just specify one of the dimensions:
What if you want to “write in” the elements by row, instead of down columns?
Matrices do not have to be numerical:
You can convert a matrix to a regular vector:
You can give your matrix row and column-names!
numbersMat YourselfPlease run this code:
You subset matrices with the [ operator:
The row and column numbers are called indices.
Suppose that vector1 and vector2 are numerical vectors. Then
gives you a sub-matrix of the elements in rows and columns covered by combinations of values in the two vectors.
The sub-matrix consisting of elements in
can be gotten like this:
The sub-matrix consisting of elements in
can be gotten like this:
The sub-matrix consisting of elements in
can be gotten like this:
If you only want to pick from one row (or one column) then you don’t get a matrix back.
The result is a vector, not a matrix. (Usually that’s what you want.)
Set the drop parameter to FALSE:
Don’t ask for rows or columns that your matrix does not have:
… works just as with ordinary vectors:
… works just as with ordinary vectors:
You can assign to more than one place in a matrix:
A B C D
a 1 7 13 19
b 0 0 0 0
c 3 9 15 21
d 4 10 16 22
e 5 11 17 23
f 6 12 18 24
The 0 was recycled to make this happen!
You can assign different values to different places.
Here are two 2-by-2 matrices:
Matrices add element-wise:
Subtraction, division, etc. all work the element-wise as well.
Suppose we have:
Multiply every element of mat by 2:
This is the same as:
* does not do the matrix multiplication that we do in Linear Algebra.
To learn how R does “real” matrix multiplication, study the textbook.
Boolean operations apply to matrices element-wise. The result is a matrix of logical values. Consider the original matrix numbersMat:
Determine which elements of numbersMat are odd:
We can select elements from a matrix using a Boolean operator:
The result is an ordinary, one-dimensional vector.