NamedRowArrays
NamedRowArrays provides an array type that knows about its row names. This allows for indexing by name in a straightforward manner in addition to the regular indexing possibilities.
These arrays are broadcastable, but note that the broadcasting behavior is undefined when broadcasting over two equally sized NamedRowArrays with different row names. In such cases, one or both of the arrays should be collected: collect(A)
NamedRowArrays.NamedRowArray
— TypeA NamedRowArray is an AbstractArray that wraps another AbstractArray (only AbstractVector and AbstractMatrix, however) and adds row names to the first array dimension. NamedRowArrays can be indexed by using the named rows as an alternative to positional indexing by dimension.
Type parameters
The NamedRowArray contains several type parameters:
struct NamedRowArray{T,N,D,R} <: AbstractArray{T,N}
T
: the elemental type of the AbstractArrayN
: the number of dimensionsD
: the type of the wrapped AbstractArrayR
: the names of the rows, as a NTuple{N, Symbol}
Constructors
When constructing a NamedRowArray, note that no copy of the array is made.
NamedRowArray(A::AbstractArray, rownames::Tuple)
NamedRowArray(A::AbstractArray, rownames::AbstractVector)
Indexing
NamedRowArrays can be indexed in the same way as normal AbstractArrays. In addition, one can also use the rownames instead of the numerical indices. Since only the rows can have names, it is also possible to obtain one or more rows of a Matrix by only passing one or more row names as the index.
Examples
For a Vector:
v = NamedRowArray(rand(3), [:a, :b, :c])
v[1] # scalar value
v[:a] # scalar value
v[2:3] # 2-element NamedRowVector
v[[:a, :b]] # 2-element NamedRowVector
For a Matrix:
a = NamedRowArray(rand(3, 10), [:a, :b, :c])
a[1, 3] # scalar value
a[:a, 3] # scalar value
a[:a, 2:3] # 2-element Vector
a[:a] # whole row: 10-element Vector
a[[:a, :b]] # two rows: 2×10 NamedRowMatrix
a[:, 3] # one column: 3-element NamedRowVector
a[:, 2:3] # two columns: 3×2 NamedRowMatrix
Inverted Indexing
Finally, it is also possible to use inverted indexes with NamedRowArrays by using the exported Not
struct from InvertedIndices.jl. In contrast to the usual behavior of Not
, using row names that do not exist will not throw an error, but will silently ignore them.
v[Not(:a)] # 3-element NamedRowVector
v[Not(:a, :c)] # 2-element NamedRowVector
a[Not(:a)] # three rows: 3×10 NamedRowMatrix
a[Not(:a), 2:3] # three rows, two columns: 3×2 NamedRowMatrix
a[Not(:a), 2] # 3-element NamedRowVector
NamedRowArrays.NamedRowMatrix
— TypeNamedRowMatrix{T,D,R}
Alias for NamedRowArray{T,2,D,R}
.
NamedRowArrays.NamedRowVector
— TypeNamedRowVector{T,D,R}
Alias for NamedRowArray{T,1,D,R}
.
Base.names
— MethodBase.names(A::NamedRowArray)
Returns the row names of A as an NTuple.
NamedRowArrays._find_nra
— MethodA = find_aac(As)
returns the first NamedRowArray among the arguments.