Skip to content

Commit

Permalink
Finixh #58 by adding the vardim keyword argument to Tables.matrix, al… (
Browse files Browse the repository at this point in the history
#66)

* Finixh #58 by adding the vardim keyword argument to Tables.matrix, allowing the user to specify whether input columns should be materialized as matrix columns or rows

* Rename vardim to dims

* Rename dims argument for Tables.matrix to transpose
  • Loading branch information
quinnj authored Mar 11, 2019
1 parent cd6bfd1 commit 1fa8f1a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/matrix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,28 @@ function table(m::AbstractMatrix; header::Vector{Symbol}=[Symbol("Column$i") for
end

"""
Tables.matrix(table)
Tables.matrix(table; transpose::Bool=false)
Materialize any table source input as a `Matrix`. If the table column types are not homogenous,
they will be promoted to a common type in the materialized `Matrix`. Note that column names are
ignored in the conversion.
ignored in the conversion. By default, input table columns will be materialized as corresponding
matrix columns; passing `transpose=true` will transpose the input with input columns as matrix rows.
"""
function matrix(table)
function matrix(table; transpose::Bool=false)
cols = Tables.columns(table)
types = schema(cols).types
T = reduce(promote_type, types)
n, p = rowcount(cols), length(types)
mat = Matrix{T}(undef, n, p)
for (i, col) in enumerate(Tables.eachcolumn(cols))
copyto!(mat, n * (i - 1) + 1, col)
if !transpose
mat = Matrix{T}(undef, n, p)
for (i, col) in enumerate(Tables.eachcolumn(cols))
mat[:, i] = col
end
else
mat = Matrix{T}(undef, p, n)
for (i, col) in enumerate(Tables.eachcolumn(cols))
mat[i, :] = col
end
end
return mat
end
4 changes: 4 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ end
@test eltype(mat2) == Float64
@test mat2[:, 1] == nt.a
@test !Tables.istable(mat2)
mat3 = Tables.matrix(nt; transpose=true)
@test size(mat3) == (2, 3)
@test mat3[1, :] == nt.a
@test mat3[2, :] == nt.b

tbl = Tables.table(mat) |> columntable
@test keys(tbl) == (:Column1, :Column2, :Column3)
Expand Down

0 comments on commit 1fa8f1a

Please sign in to comment.