Skip to content

Add levels #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "DataAPI"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
authors = ["quinnj <[email protected]>"]
version = "1.0.1"
version = "1.1.0"

[compat]
julia = "1"
Expand Down
20 changes: 20 additions & 0 deletions src/DataAPI.jl
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,26 @@ definition.
"""
function describe end

"""
levels(x)

Return a vector of unique values which occur or could occur in collection `x`,
omitting `missing` even if present. Values are returned in the preferred order
for the collection, with the result of [`sort`](@ref) as a default.

Contrary to [`unique`](@ref), this function may return values which do not
actually occur in the data, and does not preserve their order of appearance in `x`.
"""
function levels(x)
T = Base.nonmissingtype(eltype(x))
levs = convert(AbstractArray{T}, filter!(!ismissing, unique(x)))
try
sort!(levs)
catch
end
levs
end

"""
Between(first, last)

Expand Down
30 changes: 30 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,36 @@ end

end

@testset "levels" begin

@test DataAPI.levels(1:1) ==
DataAPI.levels([1]) ==
DataAPI.levels([1, missing]) ==
DataAPI.levels([missing, 1]) ==
[1]
@test DataAPI.levels(2:-1:1) ==
DataAPI.levels([2, 1]) ==
DataAPI.levels(Any[2, 1]) ==
DataAPI.levels([2, missing, 1]) ==
[1, 2]
@test DataAPI.levels([missing, "a", "c", missing, "b"]) == ["a", "b", "c"]
@test DataAPI.levels([Complex(0, 1), Complex(1, 0), missing]) ==
[Complex(0, 1), Complex(1, 0)]
@test typeof(DataAPI.levels([1])) ===
typeof(DataAPI.levels([1, missing])) ===
Vector{Int}
@test typeof(DataAPI.levels(["a"])) ===
typeof(DataAPI.levels(["a", missing])) ===
Vector{String}
@test typeof(DataAPI.levels(Real[1])) ===
typeof(DataAPI.levels(Union{Real,Missing}[1, missing])) ===
Vector{Real}
@test typeof(DataAPI.levels(trues(1))) === Vector{Bool}
@test isempty(DataAPI.levels([missing]))
@test isempty(DataAPI.levels([]))

end

@testset "Between" begin

for x in (1, :a), y in (1, :a)
Expand Down