Skip to content

Commit bc50544

Browse files
committed
Provide formatter for labeling categories in cut function
1 parent 327bef7 commit bc50544

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

src/extras.jl

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,13 @@ also accept them.
5858
values in `x`, and the upper bound is included in the last interval.
5959
* `labels::AbstractVector=[]`: a vector of strings giving the names to use for the
6060
intervals; if empty, default labels are used.
61+
* `label_formatter::Function`: a function `f(from,to;extend=false)` that generates the labels from the left and right interval boundaries. Defaults to `string("[", from, ", ", to, extend ? "]" : ")")`, e.g. `"[1, 5)"`.
6162
* `allow_missing::Bool=true`: when `true`, values outside of breaks result in missing values.
6263
only supported when `x` accepts missing values.
6364
"""
6465
function cut(x::AbstractArray{T, N}, breaks::AbstractVector;
6566
extend::Bool=false, labels::AbstractVector{U}=String[],
67+
label_formatter=_default_formatter_,
6668
allow_missing::Bool=false) where {T, N, U<:AbstractString}
6769
if !issorted(breaks)
6870
breaks = sort(breaks)
@@ -102,12 +104,12 @@ function cut(x::AbstractArray{T, N}, breaks::AbstractVector;
102104
end
103105
levs = Vector{String}(undef, n-1)
104106
for i in 1:n-2
105-
levs[i] = string("[", from[i], ", ", to[i], ")")
107+
levs[i] = label_formatter(from[i], to[i])
106108
end
107109
if extend
108-
levs[end] = string("[", from[end], ", ", to[end], "]")
110+
levs[end] = label_formatter(from[end], to[end], extend=extend)
109111
else
110-
levs[end] = string("[", from[end], ", ", to[end], ")")
112+
levs[end] = label_formatter(from[end], to[end])
111113
end
112114
else
113115
length(labels) == n-1 || throw(ArgumentError("labels must be of length $(n-1), but got length $(length(labels))"))
@@ -128,5 +130,8 @@ Cut a numeric array into `ngroups` quantiles, determined using
128130
[`quantile`](@ref).
129131
"""
130132
cut(x::AbstractArray, ngroups::Integer;
131-
labels::AbstractVector{U}=String[]) where {U<:AbstractString} =
132-
cut(x, Statistics.quantile(x, (1:ngroups-1)/ngroups); extend=true, labels=labels)
133+
labels::AbstractVector{U}=String[], label_formatter=_default_formatter_) where {U<:AbstractString} =
134+
cut(x, Statistics.quantile(x, (1:ngroups-1)/ngroups); extend=true, labels=labels, label_formatter=label_formatter)
135+
136+
_default_formatter_(from, to; extend=false) = string("[", from, ", ", to, extend ? "]" : ")")
137+

0 commit comments

Comments
 (0)