x <- 1:100
rows <- 10
cols <- 10
# Get the item at row i, column j
i <- 7
j <- 5
x[(i - 1) * cols + j] # Don't try this at home!
[1] 65
Vectors gave us the ability to form 1 dimensional data.
If we desired data in, say, 2 dimensions, we could still use a vector.
x <- 1:100
rows <- 10
cols <- 10
# Get the item at row i, column j
i <- 7
j <- 5
x[(i - 1) * cols + j] # Don't try this at home!
[1] 65
Who wants to do that?
Thankfully, R has a set of functions that make this easy for us.
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
[1] 87
The matrix function stores the given vector in column-major order by default. Our previous code assumed row-major order.
As said, the default is column-major.
If you’d prefer row-major, call matrix
with byrow = TRUE
.
rbind
rbind
combines the rows of the inputs into a new matrix.
cbind
cbind
combines the columns of the inputs into a new matrix.
nrow
, ncol
With vectors, we use length
to obtain the number of objects. Similarly, for matrices:
Use <matrix>[i, j]
to get the value at the i
th row and j
th column.
Lists allow us to store collection of objects, as with vectors, except every object need not be the same type.
We can assign names to the objects.
Then access the objects by name with the $
operator.
As with vectors, we can access a list’s objects with indices, logical values, or names using square brackets.
Be careful! There are two types of access with lists.
The first (one set of square brackets) returns a list with only the first object.
Note that when using double square brackets [[]]
, you can only access one object at a time.
This isn’t an issue with single square brackets.
Can you guess why?