Conveniently covert between coordinate-value and array representations
Source:R/matrix.utils.R
arr_from_coo.RdThese function similarly to Matrix's utilities but is simpler and allows arbitrary baseline and handling of missing values. (It is also almost certainly much slower.) Also, since it is likely that operations will be performed on the elements of the array, their argument is first for easier piping.
Usage
arr_from_coo(x, coord, dim = lengths(dimnames), x0 = NA, dimnames = NULL)
arr_to_coo(X, x0, na.rm = FALSE)Arguments
- x
values of elements differing from the default.
- coord
an integer matrix of their indices.
- dim
dimension vector; recycled to
ncol(coord); if not given, inferred fromdimnames.- x0
the default value.
- dimnames
dimension name list.
- X
an array.
- na.rm
whether the
NAelements of the array should be omitted from the list.
Value
coo_to_arr() returns a matrix or an array.
arr_to_coo() returns a list with the following elements:
xthe values distinct from
x0coorda matrix with a column for each dimension containing indexes of values distinct from
x0dimthe dimension vector of the matrix
dimnamesthe dimension name list of the matrix
Examples
m <- matrix(rpois(25, 1), 5, 5)
arr_to_coo(m, 0L)
#> $x
#> [1] 1 2 1 1 4 3 1 2 1 3 1 1 1 1 3 1
#>
#> $coord
#> row col
#> [1,] 1 1
#> [2,] 2 1
#> [3,] 4 1
#> [4,] 1 2
#> [5,] 4 2
#> [6,] 5 2
#> [7,] 4 3
#> [8,] 5 3
#> [9,] 1 4
#> [10,] 3 4
#> [11,] 4 4
#> [12,] 5 4
#> [13,] 1 5
#> [14,] 3 5
#> [15,] 4 5
#> [16,] 5 5
#>
#> $dim
#> [1] 5 5
#>
#> $x0
#> [1] 0
#>
#> $dimnames
#> NULL
#>
stopifnot(identical(do.call(arr_from_coo, arr_to_coo(m, 0L)), m))
stopifnot(length(arr_to_coo(m, NULL)$x) == 25) # No baseline
m[sample.int(25L, 2L)] <- NA
m
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 1 0 1 1
#> [2,] 2 0 0 0 0
#> [3,] NA 0 0 3 1
#> [4,] 1 4 1 1 NA
#> [5,] 0 3 2 1 1
arr_to_coo(m, 0L) # Return NAs
#> $x
#> [1] 1 2 NA 1 1 4 3 1 2 1 3 1 1 1 1 NA 1
#>
#> $coord
#> row col
#> [1,] 1 1
#> [2,] 2 1
#> [3,] 3 1
#> [4,] 4 1
#> [5,] 1 2
#> [6,] 4 2
#> [7,] 5 2
#> [8,] 4 3
#> [9,] 5 3
#> [10,] 1 4
#> [11,] 3 4
#> [12,] 4 4
#> [13,] 5 4
#> [14,] 1 5
#> [15,] 3 5
#> [16,] 4 5
#> [17,] 5 5
#>
#> $dim
#> [1] 5 5
#>
#> $x0
#> [1] 0
#>
#> $dimnames
#> NULL
#>
arr_to_coo(m, 0L, na.rm = TRUE) # Drop NAs
#> $x
#> [1] 1 2 1 1 4 3 1 2 1 3 1 1 1 1 1
#>
#> $coord
#> row col
#> [1,] 1 1
#> [2,] 2 1
#> [3,] 4 1
#> [4,] 1 2
#> [5,] 4 2
#> [6,] 5 2
#> [7,] 4 3
#> [8,] 5 3
#> [9,] 1 4
#> [10,] 3 4
#> [11,] 4 4
#> [12,] 5 4
#> [13,] 1 5
#> [14,] 3 5
#> [15,] 5 5
#>
#> $dim
#> [1] 5 5
#>
#> $x0
#> [1] 0
#>
#> $dimnames
#> NULL
#>