-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathabstractdataset.jl
More file actions
1531 lines (1325 loc) · 51.2 KB
/
abstractdataset.jl
File metadata and controls
1531 lines (1325 loc) · 51.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
AbstractDataset
An abstract type for which all concrete types expose an interface
for working with tabular data.
# Common methods
An `AbstractDataset` is a two-dimensional table with `Symbol`s or strings
for column names.
The following are normally implemented for AbstractDatasets:
* [`describe`](@ref) : summarize columns
* `summary` : show number of rows and columns
* `hcat` : horizontal concatenation
* `vcat` : vertical concatenation
* [`repeat`](@ref) : repeat rows
* `names` : columns names
* [`rename!`](@ref) : rename columns names based on keyword arguments
* `length` : number of columns
* `size` : (nrows, ncols)
* [`first`](@ref) : first `n` rows
* [`last`](@ref) : last `n` rows
* `convert` : convert to an array
* [`completecases`](@ref) : boolean vector of complete cases (rows with no missings)
* [`dropmissing`](@ref) : remove rows with missing values
* [`dropmissing!`](@ref) : remove rows with missing values in-place
* [`duplicates`](@ref) : indexes of duplicate rows
* [`unique`](@ref) : remove duplicate rows
* [`unique!`](@ref) : remove duplicate rows in-place
# Indexing and broadcasting
`AbstractDataset` can be indexed by passing two indices specifying
row and column selectors. The allowed indices are a superset of indices
that can be used for standard arrays. You can also access a single column
of an `AbstractDataset` using `getproperty` and `setproperty!` functions.
Columns can be selected using integers, `Symbol`s, or strings.
In broadcasting `AbstractDataset` behavior is similar to a `Matrix`.
A detailed description of `getindex`, `setindex!`, `getproperty`, `setproperty!`,
"""
abstract type AbstractDataset end
# DatasetColumn is a representation of a column of data set
# it is wrapped into a new type to make sure that when ever a column is
# selected, the data set is attached to it
struct DatasetColumn{T <: AbstractDataset, E}
col::Int
ds::T
val::E
end
struct SubDatasetColumn{T <: AbstractDataset, E}
col::Int
ds::T
val::E
selected_index
end
_columns(ds::AbstractDataset) = getfield(ds, :columns)
Base.show(io::IO, ::MIME"text/plain", col::DatasetColumn) = show(IOContext(io, :limit => true), "text/plain", col.val)
Base.show(io::IO, ::MIME"text/plain", col::SubDatasetColumn) = show(IOContext(io, :limit => true), "text/plain", view(col.val, col.selected_index))
_getnames(x::NamedTuple) = propertynames(x)
_getnames(x::AbstractDataset) = _names(x)
# Base.Generator(f, col::SubOrDSCol) = Base.Generator(f, __!(col))
##############################################################################
##
## Basic properties of a Dataset
##
##############################################################################
"""
names(df::AbstractDataset)
names(df::AbstractDataset, cols)
Return a freshly allocated `Vector{String}` of names of columns contained in `df`.
If `cols` is passed then restrict returned column names to those matching the
selector (this is useful in particular with regular expressions, `Cols`, `Not`, and `Between`).
`cols` can be:
* any column selector ($COLUMNINDEX_STR; $MULTICOLUMNINDEX_STR)
* a `Type`, in which case names of columns whose `eltype` is a subtype of `T`
are returned
* a `Function` predicate taking the column name as a string and returning `true`
for columns that should be kept
See also [`propertynames`](@ref) which returns a `Vector{Symbol}`.
"""
Base.names(ds::AbstractDataset, cols::Colon=:) = names(index(ds))
function Base.names(ds::AbstractDataset, cols)
nms = _names(index(ds))
idx = index(ds)[cols]
idxs = idx isa Int ? (idx:idx) : idx
return [String(nms[i]) for i in idxs]
end
Base.names(ds::AbstractDataset, T::Type) =
[String(n) for (n, c) in pairs(eachcol(ds)) if eltype(c) <: Union{Missing, T}]
Base.names(ds::AbstractDataset, fun::Function) = filter!(fun, names(ds))
# _names returns Vector{Symbol} without copying
_names(ds::AbstractDataset) = _names(index(ds))
_getformats(ds::AbstractDataset) = index(ds).format
rows(ds::AbstractDataset) = 1:nrow(ds)
# separate methods are needed due to dispatch ambiguity
Compat.hasproperty(df::AbstractDataset, s::Symbol) = haskey(index(df), s)
Compat.hasproperty(df::AbstractDataset, s::AbstractString) = haskey(index(df), s)
##############################################################################
##
## getting, setting and removing formats
##
##############################################################################
function getformat(ds::AbstractDataset, idx::Integer)
getformat(index(ds), idx)
end
function getformat(ds::AbstractDataset, y::Symbol)
getformat(index(ds), y)
end
function getformat(ds::AbstractDataset, y::String)
getformat(index(ds), y)
end
# function getformat(ds, cols::MultiColumnIndex = :)
# colsidx = index(ds)[cols]
# f_v = Dict{Symbol, Function}()
# vnm = _names(ds)
# for j in 1:length(colsidx)
# current_format = getformat(ds, colsidx[j])
# if current_format != identity
# push!(f_v, vnm[colsidx[j]]=> current_format)
# end
# end
# f_v
# end
# using Core.Compiler.return_type to check if f make sense for selected column
# this cannot take care of situations like setting sqrt for negative numbers
function _check_format_validity(ds, col, f)
flag = false
string(nameof(f))[1] == '#' && return flag
Core.Compiler.return_type(f, (eltype(ds[!, col].val), )) == Union{} && return flag
flag = true
end
#Modify Dataset
"""
setformat!(ds::Dataset, col, f)
setformat!(ds::Dataset, col => f)
setformat!(ds::Dataset, col1 => f1, col2 => f2, ...)
setformat!(ds::Dataset, cols => f)
sets specified formats for the selected `columns` of `ds`.
"""
function setformat!(ds::AbstractDataset, idx::Integer, f::Function)
!_check_format_validity(ds, idx, f) && return ds
setformat!(index(ds), idx, f)
_modified(_attributes(ds))
ds
end
function setformat!(ds::AbstractDataset, idx::Symbol, f::Function)
!_check_format_validity(ds, idx, f) && return ds
setformat!(index(ds), idx, f)
_modified(_attributes(ds))
ds
end
function setformat!(ds::AbstractDataset, idx::T, f::Function) where T <: AbstractString
!_check_format_validity(ds, idx, f) && return ds
setformat!(index(ds), idx, f)
_modified(_attributes(ds))
ds
end
function setformat!(ds::AbstractDataset, p::Pair{Int64, T}) where T <: Function
!_check_format_validity(ds, p.first, p.second) && return ds
setformat!(index(ds), p)
_modified(_attributes(ds))
ds
end
function setformat!(ds::AbstractDataset, p::Pair{Symbol, T}) where T <: Function
!_check_format_validity(ds, p.first, p.second) && return ds
setformat!(index(ds), p)
_modified(_attributes(ds))
ds
end
function setformat!(ds::AbstractDataset, p::Pair{S, T}) where S <: AbstractString where T <: Function
!_check_format_validity(ds, p.first, p.second) && return ds
setformat!(index(ds), p)
_modified(_attributes(ds))
ds
end
function setformat!(ds::AbstractDataset, p::Pair{MC, T}) where T <: Function where MC <: MultiColumnIndex
idx = index(ds)[p.first]
for i in 1:length(idx)
!_check_format_validity(ds, idx[i], p.second) && continue
setformat!(index(ds), idx[i], p.second)
# if for any reason one of the formatting is not working, we make sure the modified is correct
_modified(_attributes(ds))
end
ds
end
function setformat!(ds::AbstractDataset, dict::Dict)
for (k, v) in dict
!_check_format_validity(ds, k, v) && continue
setformat!(ds, k, v)
end
ds
end
# TODO should we allow arbitarary combination of Pair
function setformat!(ds::AbstractDataset, pv::Vector)
for p in pv
!_check_format_validity(ds, p.first, p.second) && continue
setformat!(index(ds), p)
# if for any reason one of the formatting is not working, we make sure the modified is correct
_modified(_attributes(ds))
end
ds
end
function setformat!(ds::AbstractDataset, @nospecialize(args...))
for i in 1:length(args)
!_check_format_validity(ds, args[i].first, args[i].second) && continue
setformat!(ds, args[i])
end
ds
end
setformat!(ds::AbstractDataset) = throw(ArgumentError("the columns and the format must be specified"))
# removing formats
"""
removeformat!(ds::Dataset, cols)
removes format from selected `cols` in `ds`.
"""
function removeformat!(ds::AbstractDataset, idx::Integer)
removeformat!(index(ds), idx)
_modified(_attributes(ds))
ds
end
function removeformat!(ds::AbstractDataset, y::Symbol)
removeformat!(index(ds), y)
_modified(_attributes(ds))
ds
end
function removeformat!(ds::AbstractDataset, y::String)
removeformat!(index(ds), y)
_modified(_attributes(ds))
ds
end
function removeformat!(ds::AbstractDataset, y::UnitRange)
removeformat!(index(ds), y)
_modified(_attributes(ds))
ds
end
function removeformat!(ds::AbstractDataset, cols::MultiColumnIndex)
idx = index(ds)[cols]
for i in 1:length(idx)
removeformat!(ds, idx[i])
_modified(_attributes(ds))
end
ds
end
removeformat!(ds::AbstractDataset) = throw(ArgumentError("the `cols` argument must be specified"))
function removeformat!(ds::AbstractDataset, @nospecialize(args...))
for i in 1:length(args)
removeformat!(ds, args[i])
end
ds
end
# set info
"""
setinfo!(ds::AbstractDataset, s::String)
Set `s` as the value for the `info` meta data of `ds`.
See [`getinfo`](@ref)
"""
function setinfo!(ds::AbstractDataset, s::String)
_attributes(ds).meta.info[] = s
_modified(_attributes(ds))
s
end
"""
getinfo(ds::AbstractDataset)
Get information set by `setinfo!`.
See [`setinfo!`](@ref)
"""
function getinfo(ds::AbstractDataset)
_attributes(ds).meta.info[]
end
# TODO needs better printing
"""
content(ds::AbstractDataset; output = false)
prints the meta information about `ds` and its columns. Setting `output = true` return a vector of data sets which contains the printed information as data sets.
"""
function content(ds::AbstractDataset; output = false)
println(summary(ds))
if typeof(ds) <: SubDataset
println("-----------------------------------")
println("The parent's Meta information")
end
println(" Created: ", _attributes(ds).meta.created)
println(" Modified: ", _attributes(ds).meta.modified[])
println(" Info: ", _attributes(ds).meta.info[])
f_v = [String[], Function[], Type[]]
all_names = names(ds)
for i in 1:ncol(ds)
push!(f_v[1], all_names[i])
push!(f_v[2], getformat(ds, i))
push!(f_v[3], nonmissingtype(eltype(ds[!, i])))
end
format_ds = Dataset(f_v, [:column, :format, :eltype], copycols = false)
println("-----------------------------------")
println("Columns information ")
pretty_table(format_ds, header = (["col", "format", "eltype"]), alignment =:l)
if output
[Dataset(meta = ["created", "modified", "info"], value = [_attributes(ds).meta.created, _attributes(ds).meta.modified[], _attributes(ds).meta.info[]]), format_ds]
end
end
"""
rename!(ds::AbstractDataset, vals::AbstractVector{Symbol};
makeunique::Bool=false)
rename!(ds::AbstractDataset, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false)
rename!(ds::AbstractDataset, (from => to)::Pair...)
rename!(ds::AbstractDataset, d::AbstractDict)
rename!(ds::AbstractDataset, d::AbstractVector{<:Pair})
rename!(f::Function, ds::AbstractDataset)
Rename columns of `ds` in-place.
Each name is changed at most once. Permutation of names is allowed.
# Arguments
- `ds` : the `AbstractDataset`
- `d` : an `AbstractDict` or an `AbstractVector` of `Pair`s that maps
the original names or column numbers to new names
- `f` : a function which for each column takes the old name as a `String`
and returns the new name that gets converted to a `Symbol`
- `vals` : new column names as a vector of `Symbol`s or `AbstractString`s
of the same length as the number of columns in `ds`
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found; if `true`, duplicate names will be suffixed
with `_i` (`i` starting at 1 for the first duplicate).
If pairs are passed to `rename!` (as positional arguments or in a dictionary or
a vector) then:
* `from` value can be a `Symbol`, an `AbstractString` or an `Integer`;
* `to` value can be a `Symbol` or an `AbstractString`.
Mixing symbols and strings in `to` and `from` is not allowed.
See also: [`rename`](@ref)
# Examples
```jldoctest
julia> ds = Dataset(i = 1, x = 2, y = 3)
1×3 Dataset
Row │ i x y
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename!(ds, Dict(:i => "A", :x => "X"))
1×3 Dataset
Row │ A X y
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename!(ds, [:a, :b, :c])
1×3 Dataset
Row │ a b c
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename!(ds, [:a, :b, :a])
ERROR: ArgumentError: Duplicate variable names: :a. Pass makeunique=true to make them unique using a suffix automatically.
julia> rename!(ds, [:a, :b, :a], makeunique=true)
1×3 Dataset
Row │ a b a_1
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename!(uppercase, ds)
1×3 Dataset
Row │ A B A_1
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
```
"""
function rename!(ds::AbstractDataset, vals::AbstractVector{Symbol};
makeunique::Bool=false)
# Modify Dataset
rename!(index(ds), vals, makeunique=makeunique)
_modified(_attributes(ds))
return ds
end
function rename!(ds::AbstractDataset, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false)
rename!(index(ds), Symbol.(vals), makeunique=makeunique)
_modified(_attributes(ds))
return ds
end
function rename!(ds::AbstractDataset, args::AbstractVector{Pair{Symbol, Symbol}})
rename!(index(ds), args)
_modified(_attributes(ds))
return ds
end
function rename!(ds::AbstractDataset,
args::Union{AbstractVector{<:Pair{Symbol, <:AbstractString}},
AbstractVector{<:Pair{<:AbstractString, Symbol}},
AbstractVector{<:Pair{<:AbstractString, <:AbstractString}},
AbstractDict{Symbol, Symbol},
AbstractDict{Symbol, <:AbstractString},
AbstractDict{<:AbstractString, Symbol},
AbstractDict{<:AbstractString, <:AbstractString}})
rename!(index(ds), [Symbol(from) => Symbol(to) for (from, to) in args])
_modified(_attributes(ds))
return ds
end
function rename!(ds::AbstractDataset,
args::Union{AbstractVector{<:Pair{<:Integer, <:AbstractString}},
AbstractVector{<:Pair{<:Integer, Symbol}},
AbstractDict{<:Integer, <:AbstractString},
AbstractDict{<:Integer, Symbol}})
rename!(index(ds), [_names(ds)[from] => Symbol(to) for (from, to) in args])
_modified(_attributes(ds))
return ds
end
function rename!(ds::AbstractDataset, args::Pair...)
rename!(ds, collect(args))
_modified(_attributes(ds))
ds
end
function rename!(f::Function, ds::AbstractDataset)
rename!(f, index(ds))
_modified(_attributes(ds))
return ds
end
"""
rename(ds::AbstractDataset, vals::AbstractVector{Symbol};
makeunique::Bool=false)
rename(ds::AbstractDataset, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false)
rename(ds::AbstractDataset, (from => to)::Pair...)
rename(ds::AbstractDataset, d::AbstractDict)
rename(ds::AbstractDataset, d::AbstractVector{<:Pair})
rename(f::Function, ds::AbstractDataset)
Create a new data set that is a copy of `ds` with changed column names.
Each name is changed at most once. Permutation of names is allowed.
# Arguments
- `ds` : the `AbstractDataset`; if it is a `SubDataset` then renaming is
only allowed if it was created using `:` as a column selector.
- `d` : an `AbstractDict` or an `AbstractVector` of `Pair`s that maps
the original names or column numbers to new names
- `f` : a function which for each column takes the old name as a `String`
and returns the new name that gets converted to a `Symbol`
- `vals` : new column names as a vector of `Symbol`s or `AbstractString`s
of the same length as the number of columns in `ds`
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found; if `true`, duplicate names will be suffixed
with `_i` (`i` starting at 1 for the first duplicate).
If pairs are passed to `rename` (as positional arguments or in a dictionary or
a vector) then:
* `from` value can be a `Symbol`, an `AbstractString` or an `Integer`;
* `to` value can be a `Symbol` or an `AbstractString`.
Mixing symbols and strings in `to` and `from` is not allowed.
See also: [`rename!`](@ref)
# Examples
```jldoctest
julia> ds = Dataset(i = 1, x = 2, y = 3)
1×3 Dataset
Row │ i x y
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename(ds, :i => :A, :x => :X)
1×3 Dataset
Row │ A X y
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename(ds, :x => :y, :y => :x)
1×3 Dataset
Row │ i y x
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename(ds, [1 => :A, 2 => :X])
1×3 Dataset
Row │ A X y
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename(ds, Dict("i" => "A", "x" => "X"))
1×3 Dataset
Row │ A X y
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
julia> rename(uppercase, ds)
1×3 Dataset
Row │ I X Y
│ identity identity identity
│ Int64? Int64? Int64?
─────┼──────────────────────────────
1 │ 1 2 3
```
"""
rename(ds::AbstractDataset, vals::AbstractVector{Symbol};
makeunique::Bool=false) = rename!(copy(ds), vals, makeunique=makeunique)
rename(ds::AbstractDataset, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false) = rename!(copy(ds), vals, makeunique=makeunique)
rename(ds::AbstractDataset, args...) = rename!(copy(ds), args...)
rename(f::Function, ds::AbstractDataset) = rename!(f, copy(ds))
"""
size(ds::AbstractDataset[, dim])
Return a tuple containing the number of rows and columns of `ds`.
Optionally a dimension `dim` can be specified, where `1` corresponds to rows
and `2` corresponds to columns.
See also: [`nrow`](@ref), [`ncol`](@ref)
# Examples
```jldoctest
julia> ds = Dataset(a=1:3, b='a':'c');
julia> size(ds)
(3, 2)
julia> size(ds, 1)
3
```
"""
Base.size(ds::AbstractDataset) = (nrow(ds), ncol(ds))
function Base.size(ds::AbstractDataset, i::Integer)
if i == 1
nrow(ds)
elseif i == 2
ncol(ds)
else
throw(ArgumentError("Datasets only have two dimensions"))
end
end
Base.isempty(ds::AbstractDataset) = size(ds, 1) == 0 || size(ds, 2) == 0
if VERSION < v"1.6"
Base.firstindex(ds::AbstractDataset, i::Integer) = first(axes(ds, i))
Base.lastindex(ds::AbstractDataset, i::Integer) = last(axes(ds, i))
end
Base.axes(ds::AbstractDataset, i::Integer) = Base.OneTo(size(ds, i))
"""
ndims(::AbstractDataset)
ndims(::Type{<:AbstractDataset})
Return the number of dimensions of a data set, which is always `2`.
"""
Base.ndims(::AbstractDataset) = 2
Base.ndims(::Type{<:AbstractDataset}) = 2
# separate methods are needed due to dispatch ambiguity
Base.getproperty(ds::AbstractDataset, col_ind::Symbol) = ds[!, col_ind]
Base.getproperty(ds::AbstractDataset, col_ind::AbstractString) = ds[!, col_ind]
# Private fields are never exposed since they can conflict with column names
"""
propertynames(ds::AbstractDataset)
Return a freshly allocated `Vector{Symbol}` of names of columns contained in `ds`.
"""
Base.propertynames(ds::AbstractDataset, private::Bool=false) = copy(_names(ds))
##############################################################################
##
## Similar
##
##############################################################################
"""
similar(ds::AbstractDataset, rows::Integer=nrow(ds))
Create a new `Dataset` with the same column names and column element types
as `ds`. An optional second argument can be provided to request a number of rows
that is different than the number of rows present in `ds`.
"""
function Base.similar(ds::AbstractDataset, rows::Integer = size(ds, 1))
rows < 0 && throw(ArgumentError("the number of rows must be non-negative"))
# Create Dataset
newds = Dataset(AbstractVector[similar(x, rows) for x in eachcol(ds)], copy(index(ds)),
copycols=false)
setinfo!(newds, _attributes(ds).meta.info[])
newds
end
"""
empty(ds::AbstractDataset)
Create a new `Dataset` with the same column names and column element types
as `ds` but with zero rows.
"""
Base.empty(ds::AbstractDataset) = similar(ds, 0)
##############################################################################
##
## Equality
##
##############################################################################
Base.:(==)(ds1::AbstractDataset, ds2::AbstractDataset) = isequal(ds1, ds2)
function Base.isequal(ds1::AbstractDataset, ds2::AbstractDataset)
size(ds1, 2) == size(ds2, 2) || return false
isequal(index(ds1), index(ds2)) || return false
for idx in 1:size(ds1, 2)
isequal(ds1[!, idx], ds2[!, idx]) || return false
end
return true
end
"""
isapprox(ds1::AbstractDataset, ds2::AbstractDataset;
rtol::Real=atol>0 ? 0 : √eps, atol::Real=0,
nans::Bool=false, norm::Function=norm)
Inexact equality comparison. `ds1` and `ds2` must have the same size and column names.
Return `true` if `isapprox` with given keyword arguments
applied to all pairs of columns stored in `ds1` and `ds2` returns `true`.
"""
function Base.isapprox(ds1::AbstractDataset, ds2::AbstractDataset;
atol::Real=0, rtol::Real=atol>0 ? 0 : √eps(),
nans::Bool=false, norm::Function=norm)
if size(ds1) != size(ds2)
throw(DimensionMismatch("dimensions must match: a has dims " *
"$(size(ds1)), b has dims $(size(ds2))"))
end
if !isequal(index(ds1), index(ds2))
throw(ArgumentError("column names of passed data sets do not match"))
end
return all(isapprox.(eachcol(ds1), eachcol(ds2), atol=atol, rtol=rtol, nans=nans, norm=norm))
end
##############################################################################
##
## Description
##
##############################################################################
"""
only(ds::AbstractDataset)
If `ds` has a single row return it as a `DatasetRow`; otherwise throw `ArgumentError`.
"""
function only(ds::AbstractDataset)
nrow(ds) != 1 && throw(ArgumentError("data set must contain exactly 1 row"))
return ds[1, :]
end
"""
first(ds::AbstractDataset)
Get the first row of `ds` as a `DatasetRow`.
"""
Base.first(ds::AbstractDataset) = ds[1, :]
"""
first(ds::AbstractDataset, n::Integer)
Get a data set with the `n` first rows of `ds`.
"""
Base.first(ds::AbstractDataset, n::Integer) = ds[1:min(n, nrow(ds)), :]
"""
last(ds::AbstractDataset)
Get the last row of `ds` as a `DatasetRow`.
"""
Base.last(ds::AbstractDataset) = ds[nrow(ds), :]
"""
last(ds::AbstractDataset, n::Integer)
Get a data set with the `n` last rows of `ds`.
"""
Base.last(ds::AbstractDataset, n::Integer) = ds[max(1, nrow(ds)-n+1):nrow(ds), :]
##############################################################################
##
## Miscellaneous
##
##############################################################################
"""
completecases(ds::AbstractDataset, cols=:; mapformats = false, threads)
Return a Boolean vector with `true` entries indicating rows without missing values
(complete cases) in data set `ds`.
If `cols` is provided, only missing values in the corresponding columns are considered.
`cols` can be any column selector ($COLUMNINDEX_STR; $MULTICOLUMNINDEX_STR).
See also: [`dropmissing`](@ref).
Use `findall(completecases(ds))` to get the indices of the rows.
# Examples
```jldoctest
julia> ds = Dataset(i = 1:5,
x = [missing, 4, missing, 2, 1],
y = [missing, missing, "c", "d", "e"])
5×3 Dataset
Row │ i x y
│ identity identity identity
│ Int64? Int64? String?
─────┼──────────────────────────────
1 │ 1 missing missing
2 │ 2 4 missing
3 │ 3 missing c
4 │ 4 2 d
5 │ 5 1 e
julia> completecases(ds)
5-element BitVector:
0
0
0
1
1
julia> completecases(ds, :x)
5-element BitVector:
0
1
0
1
1
julia> completecases(ds, [:x, :y])
5-element BitVector:
0
0
0
1
1
```
"""
function completecases(ds::AbstractDataset, cols::MultiColumnIndex = :; mapformats = false, threads = nrow(ds)>__NCORES*10)
if mapformats
colsidx = index(ds)[cols]
by = Function[]
for j in 1:length(colsidx)
push!(by, !ismissing∘getformat(ds, colsidx[j]))
end
byrow(ds, all, cols, by = by, threads = threads)
else
byrow(ds, all, cols, by = !ismissing, threads = threads)
end
end
completecases(ds::AbstractDataset, col::ColumnIndex; mapformats = false, threads = nrow(ds)>__NCORES*10) = completecases(ds, [col]; mapformats = mapformats, threads = threads)
"""
dropmissing(ds::AbstractDataset, cols=:; view::Bool=false, mapformats = false, threads)
Return a data set excluding rows with missing values in `ds`.
If `cols` is provided, only missing values in the corresponding columns are considered.
`cols` can be any column selector ($COLUMNINDEX_STR; $MULTICOLUMNINDEX_STR).
If `view=false` a freshly allocated `Dataset` is returned.
If `view=true` then a `SubDataset` view into `ds` is returned.
See also: [`completecases`](@ref) and [`dropmissing!`](@ref).
# Examples
```jldoctest
julia> ds = Dataset(i = 1:5,
x = [missing, 4, missing, 2, 1],
y = [missing, missing, "c", "d", "e"])
5×3 Dataset
Row │ i x y
│ identity identity identity
│ Int64? Int64? String?
─────┼──────────────────────────────
1 │ 1 missing missing
2 │ 2 4 missing
3 │ 3 missing c
4 │ 4 2 d
5 │ 5 1 e
julia> dropmissing(ds)
2×3 Dataset
Row │ i x y
│ identity identity identity
│ Int64? Int64? String?
─────┼──────────────────────────────
1 │ 4 2 d
2 │ 5 1 e
julia> dropmissing(ds, :x)
3×3 Dataset
Row │ i x y
│ identity identity identity
│ Int64? Int64? String?
─────┼──────────────────────────────
1 │ 2 4 missing
2 │ 4 2 d
3 │ 5 1 e
julia> dropmissing(ds, [:x, :y])
2×3 Dataset
Row │ i x y
│ identity identity identity
│ Int64? Int64? String?
─────┼──────────────────────────────
1 │ 4 2 d
2 │ 5 1 e
```
"""
@inline function dropmissing(ds::AbstractDataset,
cols::Union{ColumnIndex, MultiColumnIndex}=:;
view::Bool=false, mapformats = false, threads = nrow(ds)>__NCORES*10)
rowidxs = completecases(ds, cols; mapformats = mapformats, threads = threads)
if view
return Base.view(ds, rowidxs, :)
else
newds = ds[rowidxs, :]
return newds
end
end
function Base.Matrix(ds::AbstractDataset)
T = mapreduce(eltype, promote_type, _columns(ds))
return Matrix{T}(ds)
end
function Base.Matrix{T}(ds::AbstractDataset) where T
n, p = size(ds)
res = Matrix{T}(undef, n, p)
idx = 1
for (name, col) in pairs(eachcol(ds))
try
copyto!(res, idx, col)
catch err
if err isa MethodError && err.f == convert &&
!(T >: Missing) && any(ismissing, col)
throw(ArgumentError("cannot convert a Dataset containing missing " *
"values to Matrix{$T} (found for column $name)"))
else
rethrow(err)
end
end
idx += n
end
return res
end
Base.Array(ds::AbstractDataset) = Matrix(ds)
Base.Array{T}(ds::AbstractDataset) where {T} = Matrix{T}(ds)
"""
duplicates(ds::AbstractDataset; [mapformats = false, leave = :first, threads])
duplicates(ds::AbstractDataset, cols; [mapformats = false, leave = :first, threads])
Return a `BitVector` in which `true` entries indicate duplicate rows.
A row is a duplicate if there exists a prior row (default behavior, see the `leave` keyword argument for other options) with all columns containing
equal values (according to `isequal`).
If `mapformats = true` the values are checked based on their formatted values.
The `leave` keyword argument determines which occurance of duplicated rows should be indicated as non-duplicate rows.
* `leave = :first` means that everey occurance after the first one be marked as duplicate rows,
* `leave = :last` means that every occurance before the last one be marked as duplicate rows,
* `leave = :none` means that every occurance of duplicates rows be marked as duplicate rows,
* `leave = :random` means that a random occurance of duplicate rows be marked as duplicate rows.
See also [`unique`](@ref) and [`unique!`](@ref).
# Arguments
- `ds` : `AbstractDataset`
- `cols` : a selector specifying the column(s)
# Examples
```jldoctest
julia> ds = Dataset(i = 1:4, x = [1, 2, 1, 2])
4×2 Dataset
Row │ i x
│ identity identity
│ Int64? Int64?
─────┼────────────────────
1 │ 1 1
2 │ 2 2
3 │ 3 1
4 │ 4 2
julia> ds = vcat(ds, ds)
8×2 Dataset
Row │ i x
│ identity identity
│ Int64? Int64?
─────┼────────────────────
1 │ 1 1
2 │ 2 2
3 │ 3 1
4 │ 4 2
5 │ 1 1
6 │ 2 2
7 │ 3 1
8 │ 4 2
julia> duplicates(ds)
8-element Vector{Bool}:
0
0
0
0
1
1
1
1
julia> duplicates(ds, 2)
8-element Vector{Bool}:
0
0
1
1
1
1
1
1
```
"""
duplicates
function duplicates(ds::AbstractDataset, cols::MultiColumnIndex = :; mapformats = false, leave = :first, threads = true)
# :xor, :nor, :and, :or are undocumented
!(leave in (:first, :last, :none, :random, :xor, :nand, :nor, :and, :or)) && throw(ArgumentError("`leave` must be either `:first`, `:last`, `:none`, or `random`"))
if ncol(ds) == 0
throw(ArgumentError("finding duplicate rows in data set with no " *
"columns is not allowed"))
end
groups, gslots, ngroups = _gather_groups(ds, cols, nrow(ds) < typemax(Int32) ? Val(Int32) : Val(Int64), mapformats = mapformats, stable = false, threads = threads)
if leave === :random
return _nonunique_random_leave(groups, ngroups, nrow(ds))
end
res = trues(nrow(ds))
seen_groups = falses(ngroups)
if leave === :first