Skip to content

Commit a96b5b5

Browse files
authored
Support rekeying a KeyedArray (#63)
* Support various kinds of rekeying/renaming keys. * Simplify revise rekey signatures and try to keep things tuple-ish. * Dropped method to rekey and rename at the same time * Bump patch release since we're pre-1.0
1 parent 9374445 commit a96b5b5

File tree

4 files changed

+36
-2
lines changed

4 files changed

+36
-2
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "AxisKeys"
22
uuid = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
33
license = "MIT"
4-
version = "0.2.9"
4+
version = "0.2.10"
55

66
[deps]
77
AbstractFFTs = "621f4979-c628-5d54-868e-fcf4e3e8185c"

src/AxisKeys.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ export KeyedArray, axiskeys
66
include("lookup.jl")
77

88
include("names.jl")
9-
export named_axiskeys
9+
export named_axiskeys, rekey
1010
export NamedDimsArray, dimnames, rename # Reexport key NamedDimsArrays things
1111

1212
include("wrap.jl")

src/names.jl

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,27 @@ function named_axiskeys(A::AbstractArray)
173173
NT = NamedTuple{dimnames(A)}
174174
NT(axiskeys(A))
175175
end
176+
177+
178+
"""
179+
rekey(A, (1:10, [:a, :b]))
180+
rekey(A, 2 => [:a, :b])
181+
rekey(A, :y => [:a, :b])
182+
183+
Rekey a KeyedArray via `Tuple`s or `Pair`s, `dim => newkey`. If `A` also has named
184+
dimensions then you can also pass `dimname => newkey`.
185+
"""
186+
rekey(A::Union{KeyedArray, NdaKa}, k2::Tuple) = KeyedArray(keyless(A), k2)
187+
function rekey(A::Union{KeyedArray, NdaKa}, k2::Pair{<:Integer, <:AbstractVector}...)
188+
dims, vals = first.(k2), last.(k2)
189+
new_key = ntuple(ndims(A)) do d
190+
idx = findfirst(==(d), dims)
191+
idx === nothing ? axiskeys(A, d) : vals[idx]
192+
end
193+
return rekey(A, new_key)
194+
end
195+
196+
function rekey(A::Union{KaNda, NdaKa}, k2::Pair{Symbol, <:AbstractVector}...)
197+
pairs = map(p -> NamedDims.dim(A, p[1]) => p[2], k2)
198+
return rekey(A, pairs...)
199+
end

test/_basic.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,16 @@ end
170170

171171
@test_throws Exception N(obs=55) # ideally ArgumentError
172172
@test_throws Exception N(obs='z') # ideally BoundsError
173+
174+
new_obs = [:x, :y, :z]
175+
new_iter = 1:4
176+
177+
# Rekey with Tuple
178+
@test axiskeys(rekey(N, ([:x, :y, :z], 1:4))) == ([:x, :y, :z], 1:4)
179+
# Rekey with dim => axiskey pair
180+
@test axiskeys(rekey(N, 2 => 1:4)) == (['a', 'b', 'c'], 1:4)
181+
# Rekey with dimname => axiskey pair
182+
@test axiskeys(rekey(N, :iter => 1:4)) == (['a', 'b', 'c'], 1:4)
173183
end
174184

175185
@testset "named_axiskeys" begin

0 commit comments

Comments
 (0)