R Array


Array is R data type which has multiple dimensions. array() function creates or tests for arrays. dim() function defines the dimension of an array.

array(data=NA, dim=length(data), dimnames=NULL)


data: vector to fill the array
dim: row and col numbers

> x <- array(1:9)
> x
[1] 1 2 3 4 5 6 7 8 9
> x[5]
[1] 5


> x <- array(10:18,c(3,3))
> x
     [,1] [,2] [,3]
[1,]   10   13   16
[2,]   11   14   17
[3,]   12   15   18


Select array elements which match certain condition:

> x[x>15]
[1] 16 17 18
> ind <- which(x %% 3 == 0, arr.ind=FALSE)
> x[ind]
[1] 12 15 18


dim() converts the vector into array:

> x <- 1:64
> dim(x) <- c(2,4,8)
> is.array(x)

[1] TRUE


> x

, , 1
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8
, , 2
[,1] [,2] [,3] [,4]
[1,] 9 11 13 15
[2,] 10 12 14 16
, , 3
[,1] [,2] [,3] [,4]
[1,] 17 19 21 23
[2,] 18 20 22 24
, , 4
[,1] [,2] [,3] [,4]
[1,] 25 27 29 31
[2,] 26 28 30 32
, , 5
[,1] [,2] [,3] [,4]
[1,] 33 35 37 39
[2,] 34 36 38 40
, , 6
[,1] [,2] [,3] [,4]
[1,] 41 43 45 47
[2,] 42 44 46 48
, , 7
[,1] [,2] [,3] [,4]
[1,] 49 51 53 55
[2,] 50 52 54 56
, , 8
[,1] [,2] [,3] [,4]
[1,] 57 59 61 63
[2,] 58 60 62 64


> x[1,,]

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 9 17 25 33 41 49 57
[2,] 3 11 19 27 35 43 51 59
[3,] 5 13 21 29 37 45 53 61
[4,] 7 15 23 31 39 47 55 63


> x[1,2,]

[1] 3 11 19 27 35 43 51 59


> x[1,2,1]

[1] 3






endmemo.com © 2024  | Terms of Use | Privacy | Home