Convert between row- and column-style indexing of matrices
Source:R/rowColIndexing.r
rowColIndexing.Rd
These functions converts index values of cells between row- and column-style indexing of cells in matrices. Column indexing (the default for matrices) has the cell "1" in the upper left corner of the matrix. The cell "2" is below it, and so on. The numbering then wraps around to the top of the next column. Row indexing (the default for rasters, for example), also has cell "1" in the upper left, but cell "2" is to its right, and so on. Numbering then wraps around to the next row.
Arguments
- x
Either a matrix, or a vector with two values, one for the number of rows and one for the number of columns in a matrix.
- cell
One or more cell indices (positive integers).
- dir
The "direction" in which to convert. If
'row'
, it is assumed thatcell
is a column-style index and so should be converted to a row-style index. If'col'
, it is assumed thatcell
is a row-style index and so should be converted to a column-style index.
Examples
# column versus row indexing
colIndex <- matrix(1:40, nrow=5, ncol=8)
rowIndex <- matrix(1:40, nrow=5, ncol=8, byrow=TRUE)
colIndex
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#> [1,] 1 6 11 16 21 26 31 36
#> [2,] 2 7 12 17 22 27 32 37
#> [3,] 3 8 13 18 23 28 33 38
#> [4,] 4 9 14 19 24 29 34 39
#> [5,] 5 10 15 20 25 30 35 40
rowIndex
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#> [1,] 1 2 3 4 5 6 7 8
#> [2,] 9 10 11 12 13 14 15 16
#> [3,] 17 18 19 20 21 22 23 24
#> [4,] 25 26 27 28 29 30 31 32
#> [5,] 33 34 35 36 37 38 39 40
# examples
x <- matrix('a', nrow=5, ncol=8, byrow=TRUE)
rowColIndexing(x, cell=c(1, 6, 20), 'row')
#> [1] 1 2 36
rowColIndexing(x, cell=c(1, 6, 20), 'col')
#> [1] 1 26 18
rowColIndexing(c(5, 8), cell=c(1, 6, 20), 'row')
#> [1] 1 2 36
rowColIndexing(c(5, 8), cell=c(1, 6, 20), 'col')
#> [1] 1 26 18