-
Matrices
So far we've only worked with vectors, which are simple lists of values. What if you need data in rows and columns? Matrices are here to help.
A matrix is just a fancy term for a 2-dimensional array. In this chapter, we'll show you all the basics of working with matrices, from creating them, to accessing them, to plotting them.
-
The vector is no longer one-dimensional. It has been converted, in-place, to a matrix.
Now, use the
matrix
function to make a 5x5 matrix, with its fields initialized to any values you like.Redo Complete> matrix(1, 5, 5) [,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 1 1 [2,] 1 1 1 1 1 [3,] 1 1 1 1 1 [4,] 1 1 1 1 1 [5,] 1 1 1 1 1
-
Matrix Plotting3.3
Text output is only useful when matrices are small. When working with more complex data, you'll need something better. Fortunately, R includes powerful visualizations for matrix data.
We'll start simple, with an elevation map of a sandy beach.
It's pretty flat - everything is 1 meter above sea level. We'll create a 10 by 10 matrix with all its values initialized to 1 for you:
-
- 0.00.20.40.60.81.00.00.20.40.60.81.0
-
- elevationYZ
-
The perspective plot looks a little odd, though. This is because persp automatically expands the view so that your highest value (the beach surface) is at the very top.
We can fix that by specifying our own value for the
expand
parameter.- elevationYZ
-
Okay, those examples are a little simplistic. Thankfully, R includes some sample data sets to play around with. One of these is
volcano
, a 3D map of a dormant New Zealand volcano.It's simply an 87x61 matrix with elevation values, but it shows the power of R's matrix visualizations.
Try creating a contour map of the volcano matrix:
- 0.00.20.40.60.81.00.00.20.40.60.81.0
-
- volcanoYZ
-
- 0.00.20.40.60.81.00.00.20.40.60.81.0
-
Chapter 3 Completed
Share your plunder:
Here we stand on the beach, at the end of Chapter 3. What's this, buried in the sand? It's another badge!
In this chapter, we learned how to create matrices from scratch, and how to re-shape a vector into a matrix. We learned how to access values within a matrix one-by-one, or in groups. And we saw just a few of the ways to visualize a matrix's data.
None of the techniques we've used so far will help you describe your data, though. We'll rectify that in the next chapter, where we'll talk about summary statistics.