Understanding array indexing in R

Array R-documentation states

The values ​​in the data vector give the values ​​in the array in the same order as in FORTRAN, that is, the "main order of the column" , with the first index working fastest and the last index slower .

He then gives an explanatory example of this, loading the data into a two-dimensional array:

 > x <- array(1:20, dim=c(4,5))   # Generate a 4 by 5 array.
 > x
      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    5    9   13   17
 [2,]    2    6   10   14   18
 [3,]    3    7   11   15   19
 [4,]    4    8   12   16   20

From experience with other languages, I would have thought that x[1, 2], instead x[2, 1], will be 2, but it's pretty easy to adjust my thinking. However, as fast as I complete my mental shift of the model, the following example breaks it into pieces:

 > i <- array(c(1:3,3:1), dim=c(3,2))
 > i                             # i is a 3 by 2 index array.
      [,1] [,2]
 [1,]    1    3
 [2,]    2    2
 [3,]    3    1
 > x[i]                          # Extract those elements
 [1] 9 6 3

, , , x[1, 3], x[2,2] x[3, 1]. , " "?

, , i 2 3, R x[i] x[i[1, 1], i[2, 1]], x[i[1, 2], i[2, 2]], .... , R x[i[1, 1], i[1, 2]], x[i[2, 1], i[2, 2]], ...

R ?

+3
2

" " , - , ; .,

x[1:20]

1, 2, 3, ..., 19, 20. - , , , ... : i , x , . , i, x ... x[t(i)] is 1:20[c(1,3,2,2,3,1)].

+6

. , x. , 2- 2- , , .

R 2-.

+1
source

Source: https://habr.com/ru/post/1765710/


All Articles