From d4bbaecf17182cd9861b79450e703397a461c8f3 Mon Sep 17 00:00:00 2001 From: "David A. van Leeuwen" Date: Thu, 20 Feb 2020 10:39:55 +0100 Subject: [PATCH] Allow NamedTuple in constructor---this is the way to go, see #55 --- src/constructors.jl | 5 +++++ test/constructors.jl | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/src/constructors.jl b/src/constructors.jl index a98e560..90efa30 100644 --- a/src/constructors.jl +++ b/src/constructors.jl @@ -73,6 +73,11 @@ NamedArray(array::AbstractVector{T}, dimname=defaultdimname(1)) where {T,VT} = NamedArray(array, (names,), (dimname,)) +function NamedArray(array::AbstractArray{T,N}, names::NamedTuple) where {T, N} + length(names) == N || error("Dimension mismatch") + return NamedArray(array, values(names), keys(names)) +end + ## Type and dimensions """ `NamedArray(T::Type, dims::Int...)` creates an uninitialized array with default names diff --git a/test/constructors.jl b/test/constructors.jl index 5a64f68..1eedabd 100644 --- a/test/constructors.jl +++ b/test/constructors.jl @@ -39,6 +39,12 @@ n4 = @inferred NamedArray(a, (OrderedDict("a"=>1,"b"=>2), OrderedDict("C"=>1,"D" @test names(n3, 1) == names(n4, 1) == ["a","b"] @test names(n3, 2) == names(n4, 2) == ["C","D","E"] +## named tuples +n4 = @inferred NamedArray(a, (一=["α", "β"], 二=["أ", "ب", "ج"])) +@test dimnames(n4) == [:一, :二] +@test names(n4, 1) == ["α", "β"] +@test names(n4, 2) == ["أ", "ب", "ج"] + n1 = @inferred NamedArray([1], (BitArray([true]),)) n2 = @inferred NamedArray([1], BitArray([true])) n3 = @inferred NamedArray([1], [true])