From b6e4c6182b91ad8bd5a505564499258b2ba8b2c4 Mon Sep 17 00:00:00 2001 From: Takafumi Arakaki Date: Sun, 15 Dec 2019 09:53:35 -0800 Subject: [PATCH] Support appending arbitrary table --- src/Table.jl | 29 +++++++++++++++++++++++++++++ test/Table.jl | 8 ++++++++ 2 files changed, 37 insertions(+) diff --git a/src/Table.jl b/src/Table.jl index 9dab645..4e479ee 100644 --- a/src/Table.jl +++ b/src/Table.jl @@ -199,6 +199,35 @@ function Base.append!(t::Table{<:NamedTuple{names}}, t2::Table{<:NamedTuple{name return t end +_asnamedtuple(T) = data -> _asnamedtuple(T, data) +function _asnamedtuple(::Type{T}, data) where {names, T<:NamedTuple{names}} + if data isa NamedTuple + return T(data) + else + return T(Tuple(getproperty(data, n) for n in names)) + end +end + +function append_columnaccess!(t::Table, t2) + cols = _asnamedtuple(NamedTuple{columnnames(t)}, columns(t2)) + map(append!, columns(t), cols) + return t +end + +append_rowaccess!(t::Table, t2) = + mapfoldl(_asnamedtuple(NamedTuple{columnnames(t)}), push!, Tables.rows(t2); init = t) + +function Base.append!(t::Table, t2) + if Tables.istable(t2) + if Tables.columnaccess(t2) + return append_columnaccess!(t, t2) + elseif Tables.rowaccess(t2) + return append_rowaccess!(t, t2) + end + end + throw(ArgumentError("Cannot handle non-table type ", typeof(t2))) +end + function Base.popfirst!(t::Table) return map(popfirst!, columns(t)) end diff --git a/test/Table.jl b/test/Table.jl index 9939416..fc2437f 100644 --- a/test/Table.jl +++ b/test/Table.jl @@ -188,6 +188,14 @@ @test isequal(Table(t |> rowtable), t) end + @testset "append!(_, ::$(typeof(t2)))" for t2 in Any[ + [(a=3, b=4)], + (a=[3], b=[4]), + ] + t = Table(a=[1], b=[2]) + @test append!(t, t2) == Table(a = [1, 3], b = [2, 4]) + end + @testset "group" begin t = Table(a = [1,2,1], b = [2.0, 4.0, 6.0]) out = group(getproperty(:a), t)