rray_extract() selects values from x by 1D location or by coordinate
point. The result is always a 1D array.
rray_extract_assign() replaces the selected values with value and returns
a modified copy of x.
Arguments
- x
An array.
- i
A numeric vector of locations, a logical vector, a logical array with the same dimensions as
x, or a numeric matrix of coordinate points.- value
A 1D array to assign to the selected values. It is cast to the type of
x, then broadcast to the number of selected or missing positions. It must be size 1 or have one element per position.
Value
rray_extract()returns a one-dimensional array. Names are always dropped.rray_extract_assign()returnsxwith the selected values replaced. The type, dimensions, and names ofxare kept.
Details
The type and shape of i decide how it is used:
An integer or double vector holds 1D locations.
xis treated as its equivalent flattened array, so location4in a 2 x 3 matrix is row 2, column 2. Locations follow the usual R rules: negative values drop elements, zero is ignored, duplicates repeat elements, andNAgives a missing value.A logical vector must be size 1 or the size of
x. A logical array must have the same dimensions asx, sorray_extract(x, x > 5)works. WhenTRUE, the corresponding value inxis returned.An integer or double matrix holds coordinate points. Each row selects one element, and there must be one column per axis of
x. Coordinates must be positive and within the dimension of their axis.NAat any position within the row generates a missing value.
For raw arrays the missing value is as.raw(0), and for list arrays it is
NULL.
For assignment, a missing entry in i leaves x unchanged at that
position but uses one element of value. This also applies to a point row
with a missing coordinate. Zero locations use no element of value.
Negative locations can't be combined with missing values.
Examples
x <- array(1:24, c(2L, 3L, 4L))
# 1D locations
rray_extract(x, c(1, 4, 24))
#> [1] 1 4 24
# Negative locations drop elements
rray_extract(x, -(1:20))
#> [1] 21 22 23 24
# A logical mask with the same dimensions as `x`
rray_extract(x, x %% 5 == 0)
#> [1] 5 10 15 20
# One row per point, one column per axis
points <- rbind(
c(1, 1, 1),
c(2, 3, 4),
c(1, 2, 3)
)
rray_extract(x, points)
#> [1] 1 24 15
# Assign one value to every selected element
rray_extract_assign(x, x %% 5 == 0, 0L)
#> , , 1
#>
#> [,1] [,2] [,3]
#> [1,] 1 3 0
#> [2,] 2 4 6
#>
#> , , 2
#>
#> [,1] [,2] [,3]
#> [1,] 7 9 11
#> [2,] 8 0 12
#>
#> , , 3
#>
#> [,1] [,2] [,3]
#> [1,] 13 0 17
#> [2,] 14 16 18
#>
#> , , 4
#>
#> [,1] [,2] [,3]
#> [1,] 19 21 23
#> [2,] 0 22 24
#>
# Or one value per selected element
rray_extract_assign(x, points, c(100L, 200L, 300L))
#> , , 1
#>
#> [,1] [,2] [,3]
#> [1,] 100 3 5
#> [2,] 2 4 6
#>
#> , , 2
#>
#> [,1] [,2] [,3]
#> [1,] 7 9 11
#> [2,] 8 10 12
#>
#> , , 3
#>
#> [,1] [,2] [,3]
#> [1,] 13 300 17
#> [2,] 14 16 18
#>
#> , , 4
#>
#> [,1] [,2] [,3]
#> [1,] 19 21 23
#> [2,] 20 22 200
#>
