Introduction to Data Structures
In R, you can construct more complicated data structures than just vectors. An array is a multidimensional vector. Vectors and arrays are stored the same way internally, but an array may be displayed differently and accessed differently. An array object is just a vector that’s associated with a dimension attribute. Here’s a simple example.
First, let’s define an array explicitly:
> a <- array(c(1,2,3,4,5,6,7,8,9,10,11,12),dim=c(3,4))
Here is what the array looks like:
> a
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12And here is how you reference one cell:
> a[2,2] [1] 5
Now, let’s define a vector with the same contents:
> v <- c(1,2,3,4,5,6,7,8,9,10,11,12) > v [1] 1 2 3 4 5 6 7 8 9 10 11 12
A matrix is just a two-dimensional array:
> m <- matrix(data=c(1,2,3,4,5,6,7,8,9,10,11,12),nrow=3,ncol=4)
> m
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12Arrays can have more than two dimensions. For example:
> w <- array(c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18),dim=c(3,3,2))
> w
, , 1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
, , 2
[,1] [,2] [,3]
[1,] 10 13 16
[2,] 11 14 17
[3,] 12 15 18
> w[1,1,1]
[1] 1R uses very clean syntax for referring to part of an array. You specify separate indices for each dimension, separated by commas:
> a[1,2]
[1] 4
> a[1:2,1:2]
[,1] [,2]
[1,] 1 4
[2,] 2 5To get all rows (or columns) from a dimension, simply omit the indices:
> # first row only > a[1,] [1] 1 4 7 10 > # first column only > a[,1] [1] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access