/
vector.rb
1769 lines (1562 loc) · 52.6 KB
/
vector.rb
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
require 'daru/maths/arithmetic/vector.rb'
require 'daru/maths/statistics/vector.rb'
require 'daru/plotting/gruff.rb'
require 'daru/plotting/nyaplot.rb'
require 'daru/accessors/array_wrapper.rb'
require 'daru/accessors/nmatrix_wrapper.rb'
require 'daru/accessors/gsl_wrapper.rb'
require 'daru/category.rb'
module Daru
class Vector # rubocop:disable Metrics/ClassLength
include Enumerable
include Daru::Maths::Arithmetic::Vector
include Daru::Maths::Statistics::Vector
extend Gem::Deprecate
class << self
# Create a new vector by specifying the size and an optional value
# and block to generate values.
#
# == Description
#
# The *new_with_size* class method lets you create a Daru::Vector
# by specifying the size as the argument. The optional block, if
# supplied, is run once for populating each element in the Vector.
#
# The result of each run of the block is the value that is ultimately
# assigned to that position in the Vector.
#
# == Options
# :value
# All the rest like .new
def new_with_size n, opts={}, &block
value = opts.delete :value
block ||= ->(_) { value }
Daru::Vector.new Array.new(n, &block), opts
end
# Create a vector using (almost) any object
# * Array: flattened
# * Range: transformed using to_a
# * Daru::Vector
# * Numeric and string values
#
# == Description
#
# The `Vector.[]` class method creates a vector from almost any
# object that has a `#to_a` method defined on it. It is similar
# to R's `c` method.
#
# == Usage
#
# a = Daru::Vector[1,2,3,4,6..10]
# #=>
# # <Daru::Vector:99448510 @name = nil @size = 9 >
# # nil
# # 0 1
# # 1 2
# # 2 3
# # 3 4
# # 4 6
# # 5 7
# # 6 8
# # 7 9
# # 8 10
def [](*indexes)
values = indexes.map do |a|
a.respond_to?(:to_a) ? a.to_a : a
end.flatten
Daru::Vector.new(values)
end
def _load(data) # :nodoc:
h = Marshal.load(data)
Daru::Vector.new(h[:data],
index: h[:index],
name: h[:name],
dtype: h[:dtype], missing_values: h[:missing_values])
end
def coerce(data, options={})
case data
when Daru::Vector
data
when Array, Hash
new(data, options)
else
raise ArgumentError, "Can't coerce #{data.class} to #{self}"
end
end
end
def size
@data.size
end
def each(&block)
return to_enum(:each) unless block_given?
@data.each(&block)
self
end
def each_index(&block)
return to_enum(:each_index) unless block_given?
@index.each(&block)
self
end
def each_with_index &block
return to_enum(:each_with_index) unless block_given?
@data.to_a.zip(@index.to_a).each(&block)
self
end
def map!(&block)
return to_enum(:map!) unless block_given?
@data.map!(&block)
self
end
def apply_method(method, keys: nil, by_position: true)
vect = keys ? get_sub_vector(keys, by_position: by_position) : self
case method
when Symbol then vect.send(method)
when Proc then method.call(vect)
else raise
end
end
alias :apply_method_on_sub_vector :apply_method
# The name of the Daru::Vector. String.
attr_reader :name
# The row index. Can be either Daru::Index or Daru::MultiIndex.
attr_reader :index
# The underlying dtype of the Vector. Can be either :array, :nmatrix or :gsl.
attr_reader :dtype
# If the dtype is :nmatrix, this attribute represents the data type of the
# underlying NMatrix object. See NMatrix docs for more details on NMatrix
# data types.
attr_reader :nm_dtype
# An Array or the positions in the vector that are being treated as 'missing'.
attr_reader :missing_positions
deprecate :missing_positions, :indexes, 2016, 10
# Store a hash of labels for values. Supplementary only. Recommend using index
# for proper usage.
attr_accessor :labels
# Store vector data in an array
attr_reader :data
# TODO: Make private.
attr_reader :nil_positions, :nan_positions
# Create a Vector object.
#
# == Arguments
#
# @param source[Array,Hash] - Supply elements in the form of an Array or a
# Hash. If Array, a numeric index will be created if not supplied in the
# options. Specifying more index elements than actual values in *source*
# will insert *nil* into the surplus index elements. When a Hash is specified,
# the keys of the Hash are taken as the index elements and the corresponding
# values as the values that populate the vector.
#
# == Options
#
# * +:name+ - Name of the vector
#
# * +:index+ - Index of the vector
#
# * +:dtype+ - The underlying data type. Can be :array, :nmatrix or :gsl.
# Default :array.
#
# * +:nm_dtype+ - For NMatrix, the data type of the numbers. See the NMatrix docs for
# further information on supported data type.
#
# * +:missing_values+ - An Array of the values that are to be treated as 'missing'.
# nil is the default missing value.
#
# == Usage
#
# vecarr = Daru::Vector.new [1,2,3,4], index: [:a, :e, :i, :o]
# vechsh = Daru::Vector.new({a: 1, e: 2, i: 3, o: 4})
def initialize source, opts={}
if opts[:type] == :category
# Initialize category type vector
extend Daru::Category
initialize_category source, opts
else
# Initialize non-category type vector
initialize_vector source, opts
end
end
# attr_reader for :plotting_library
def plotting_library
init_plotting_library
@plotting_library
end
def plotting_library= lib
case lib
when :gruff, :nyaplot
@plotting_library = lib
if Daru.send("has_#{lib}?".to_sym)
extend Module.const_get(
"Daru::Plotting::Vector::#{lib.to_s.capitalize}Library"
)
end
else
raise ArgumentError, "Plotting library #{lib} not supported. "\
'Supported libraries are :nyaplot and :gruff'
end
end
# this method is overwritten: see Daru::Vector#plotting_library=
def plot(*args, **options, &b)
init_plotting_library
plot(*args, **options, &b)
end
# Get one or more elements with specified index or a range.
#
# == Usage
# # For vectors employing single layer Index
#
# v[:one, :two] # => Daru::Vector with indexes :one and :two
# v[:one] # => Single element
# v[:one..:three] # => Daru::Vector with indexes :one, :two and :three
#
# # For vectors employing hierarchial multi index
#
def [](*input_indexes)
# Get array of positions indexes
positions = @index.pos(*input_indexes)
# If one object is asked return it
return @data[positions] if positions.is_a? Numeric
# Form a new Vector using positional indexes
Daru::Vector.new(
positions.map { |loc| @data[loc] },
name: @name,
index: @index.subset(*input_indexes), dtype: @dtype
)
end
# Returns vector of values given positional values
# @param positions [Array<object>] positional values
# @return [object] vector
# @example
# dv = Daru::Vector.new 'a'..'e'
# dv.at 0, 1, 2
# # => #<Daru::Vector(3)>
# # 0 a
# # 1 b
# # 2 c
def at *positions
# to be used to form index
original_positions = positions
positions = coerce_positions(*positions)
validate_positions(*positions)
if positions.is_a? Integer
@data[positions]
else
values = positions.map { |pos| @data[pos] }
Daru::Vector.new values, index: @index.at(*original_positions), dtype: dtype
end
end
# Change value at given positions
# @param positions [Array<object>] positional values
# @param [object] val value to assign
# @example
# dv = Daru::Vector.new 'a'..'e'
# dv.set_at [0, 1], 'x'
# dv
# # => #<Daru::Vector(5)>
# # 0 x
# # 1 x
# # 2 c
# # 3 d
# # 4 e
def set_at positions, val
validate_positions(*positions)
positions.map { |pos| @data[pos] = val }
update_position_cache
end
# Just like in Hashes, you can specify the index label of the Daru::Vector
# and assign an element an that place in the Daru::Vector.
#
# == Usage
#
# v = Daru::Vector.new([1,2,3], index: [:a, :b, :c])
# v[:a] = 999
# #=>
# ##<Daru::Vector:90257920 @name = nil @size = 3 >
# # nil
# # a 999
# # b 2
# # c 3
def []=(*indexes, val)
cast(dtype: :array) if val.nil? && dtype != :array
guard_type_check(val)
modify_vector(indexes, val)
update_position_cache
end
# Two vectors are equal if they have the exact same index values corresponding
# with the exact same elements. Name is ignored.
def == other
case other
when Daru::Vector
@index == other.index && size == other.size &&
@index.all? { |index| self[index] == other[index] }
else
super
end
end
# !@method eq
# Uses `==` and returns `true` for each **equal** entry
# @param [#==, Daru::Vector] If scalar object, compares it with each
# element in self. If Daru::Vector, compares elements with same indexes.
# @example (see #where)
# !@method not_eq
# Uses `!=` and returns `true` for each **unequal** entry
# @param [#!=, Daru::Vector] If scalar object, compares it with each
# element in self. If Daru::Vector, compares elements with same indexes.
# @example (see #where)
# !@method lt
# Uses `<` and returns `true` for each entry **less than** the supplied object
# @param [#<, Daru::Vector] If scalar object, compares it with each
# element in self. If Daru::Vector, compares elements with same indexes.
# @example (see #where)
# !@method lteq
# Uses `<=` and returns `true` for each entry **less than or equal to** the supplied object
# @param [#<=, Daru::Vector] If scalar object, compares it with each
# element in self. If Daru::Vector, compares elements with same indexes.
# @example (see #where)
# !@method mt
# Uses `>` and returns `true` for each entry **more than** the supplied object
# @param [#>, Daru::Vector] If scalar object, compares it with each
# element in self. If Daru::Vector, compares elements with same indexes.
# @example (see #where)
# !@method mteq
# Uses `>=` and returns `true` for each entry **more than or equal to** the supplied object
# @param [#>=, Daru::Vector] If scalar object, compares it with each
# element in self. If Daru::Vector, compares elements with same indexes.
# @example (see #where)
# Define the comparator methods with metaprogramming. See documentation
# written above for functionality of each method. Use these methods with the
# `where` method to obtain the corresponding Vector/DataFrame.
{
eq: :==,
not_eq: :!=,
lt: :<,
lteq: :<=,
mt: :>,
mteq: :>=
}.each do |method, operator|
define_method(method) do |other|
mod = Daru::Core::Query
if other.is_a?(Daru::Vector)
mod.apply_vector_operator operator, self, other
else
mod.apply_scalar_operator operator, @data, other
end
end
alias_method operator, method if operator != :== && operator != :!=
end
alias :gt :mt
alias :gteq :mteq
# Comparator for checking if any of the elements in *other* exist in self.
#
# @param [Array, Daru::Vector] other A collection which has elements that
# need to be checked for in self.
# @example Usage of `in`.
# vector = Daru::Vector.new([1,2,3,4,5])
# vector.where(vector.in([3,5]))
# #=>
# ##<Daru::Vector:82215960 @name = nil @size = 2 >
# # nil
# # 2 3
# # 4 5
def in other
other = Hash[other.zip(Array.new(other.size, 0))]
Daru::Core::Query::BoolArray.new(
@data.each_with_object([]) do |d, memo|
memo << (other.key?(d) ? true : false)
end
)
end
# Return a new vector based on the contents of a boolean array. Use with the
# comparator methods to obtain meaningful results. See this notebook for
# a good overview of using #where.
#
# @param bool_array [Daru::Core::Query::BoolArray, Array<TrueClass, FalseClass>] The
# collection containing the true of false values. Each element in the Vector
# corresponding to a `true` in the bool_arry will be returned alongwith it's
# index.
# @example Usage of #where.
# vector = Daru::Vector.new([2,4,5,51,5,16,2,5,3,2,1,5,2,5,2,1,56,234,6,21])
#
# # Simple logic statement passed to #where.
# vector.where(vector.eq(5).or(vector.eq(1)))
# # =>
# ##<Daru::Vector:77626210 @name = nil @size = 7 >
# # nil
# # 2 5
# # 4 5
# # 7 5
# # 10 1
# # 11 5
# # 13 5
# # 15 1
#
# # A somewhat more complex logic statement
# vector.where((vector.eq(5) | vector.lteq(1)) & vector.in([4,5,1]))
# #=>
# ##<Daru::Vector:81072310 @name = nil @size = 7 >
# # nil
# # 2 5
# # 4 5
# # 7 5
# # 10 1
# # 11 5
# # 13 5
# # 15 1
def where bool_array
Daru::Core::Query.vector_where self, bool_array
end
# Return a new vector based on the contents of a boolean array and &block.
#
# @param bool_array [Daru::Core::Query::BoolArray, Array<TrueClass, FalseClass>, &block] The
# collection containing the true of false values. Each element in the Vector
# corresponding to a `true` in the bool_array will be returned along with it's
# index. The &block may contain manipulative functions for the Vector elements.
#
# @return [Daru::Vector]
#
# @example Usage of #apply_where.
# dv = Daru::Vector.new ['3 days', '5 weeks', '2 weeks']
# dv = dv.apply_where(dv.match /weeks/) { |x| "#{x.split.first.to_i * 7} days" }
# # =>
# ##<Daru::Vector(3)>
# # 0 3 days
# # 1 35 days
# # 2 14 days
def apply_where bool_array, &block
Daru::Core::Query.vector_apply_where self, bool_array, &block
end
def head q=10
self[0..(q-1)]
end
def tail q=10
start = [size - q, 0].max
self[start..(size-1)]
end
def last q=1
# The Enumerable mixin dose not provide the last method.
tail(q)
end
def empty?
@index.empty?
end
def numeric?
type == :numeric
end
def object?
type == :object
end
# Reports whether missing data is present in the Vector.
def has_missing_data?
!indexes(*Daru::MISSING_VALUES).empty?
end
alias :flawed? :has_missing_data?
deprecate :has_missing_data?, :include_values?, 2016, 10
deprecate :flawed?, :include_values?, 2016, 10
# Check if any one of mentioned values occur in the vector
# @param values [Array] values to check for
# @return [true, false] returns true if any one of specified values
# occur in the vector
# @example
# dv = Daru::Vector.new [1, 2, 3, 4, nil]
# dv.include_values? nil, Float::NAN
# # => true
def include_values?(*values)
values.any? { |v| include_with_nan? @data, v }
end
# @note Do not use it to check for Float::NAN as
# Float::NAN == Float::NAN is false
# Return vector of booleans with value at ith position is either
# true or false depending upon whether value at position i is equal to
# any of the values passed in the argument or not
# @param values [Array] values to equate with
# @return [Daru::Vector] vector of boolean values
# @example
# dv = Daru::Vector.new [1, 2, 3, 2, 1]
# dv.is_values 1, 2
# # => #<Daru::Vector(5)>
# # 0 true
# # 1 true
# # 2 false
# # 3 true
# # 4 true
def is_values(*values)
Daru::Vector.new values.map { |v| eq(v) }.inject(:|)
end
# Append an element to the vector by specifying the element and index
def concat element, index
raise IndexError, 'Expected new unique index' if @index.include? index
@index |= [index]
@data[@index[index]] = element
update_position_cache
end
alias :push :concat
alias :<< :concat
# Cast a vector to a new data type.
#
# == Options
#
# * +:dtype+ - :array for Ruby Array. :nmatrix for NMatrix.
def cast opts={}
dt = opts[:dtype]
raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt)
@data = cast_vector_to dt unless @dtype == dt
end
# Delete an element by value
def delete element
delete_at index_of(element)
end
# Delete element by index
def delete_at index
@data.delete_at @index[index]
@index = Daru::Index.new(@index.to_a - [index])
update_position_cache
end
# The type of data contained in the vector. Can be :object or :numeric. If
# the underlying dtype is an NMatrix, this method will return the data type
# of the NMatrix object.
#
# Running through the data to figure out the kind of data is delayed to the
# last possible moment.
def type
return @data.nm_dtype if dtype == :nmatrix
if @type.nil? || @possibly_changed_type
@type = :numeric
each do |e|
next if e.nil? || e.is_a?(Numeric)
@type = :object
break
end
@possibly_changed_type = false
end
@type
end
# Tells if vector is categorical or not.
# @return [true, false] true if vector is of type category, false otherwise
# @example
# dv = Daru::Vector.new [1, 2, 3], type: :category
# dv.category?
# # => true
def category?
type == :category
end
# Get index of element
def index_of element
case dtype
when :array then @index.key(@data.index { |x| x.eql? element })
else @index.key @data.index(element)
end
end
# Keep only unique elements of the vector alongwith their indexes.
def uniq
uniq_vector = @data.uniq
new_index = uniq_vector.map { |element| index_of(element) }
Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype
end
def any? &block
@data.data.any?(&block)
end
def all? &block
@data.data.all?(&block)
end
# Sorts a vector according to its values. If a block is specified, the contents
# will be evaluated and data will be swapped whenever the block evaluates
# to *true*. Defaults to ascending order sorting. Any missing values will be
# put at the end of the vector. Preserves indexing. Default sort algorithm is
# quick sort.
#
# == Options
#
# * +:ascending+ - if false, will sort in descending order. Defaults to true.
#
# * +:type+ - Specify the sorting algorithm. Only supports quick_sort for now.
# == Usage
#
# v = Daru::Vector.new ["My first guitar", "jazz", "guitar"]
# # Say you want to sort these strings by length.
# v.sort(ascending: false) { |a,b| a.length <=> b.length }
def sort opts={}, &block
opts = {ascending: true}.merge(opts)
vector_index = resort_index(@data.each_with_index, opts, &block)
vector, index = vector_index.transpose
index = @index.reorder index
Daru::Vector.new(vector, index: index, name: @name, dtype: @dtype)
end
# Sorts the vector according to it's`Index` values. Defaults to ascending
# order sorting.
#
# @param [Hash] opts the options for sort_by_index method.
# @option opts [Boolean] :ascending false, will sort `index` in
# descending order.
#
# @return [Vector] new sorted `Vector` according to the index values.
#
# @example
#
# dv = Daru::Vector.new [11, 13, 12], index: [23, 21, 22]
# # Say you want to sort index in ascending order
# dv.sort_by_index(ascending: true)
# #=> Daru::Vector.new [13, 12, 11], index: [21, 22, 23]
# # Say you want to sort index in descending order
# dv.sort_by_index(ascending: false)
# #=> Daru::Vector.new [11, 12, 13], index: [23, 22, 21]
def sort_by_index opts={}
opts = {ascending: true}.merge(opts)
_, new_order = resort_index(@index.each_with_index, opts).transpose
reorder new_order
end
DEFAULT_SORTER = lambda { |(lv, li), (rv, ri)|
case
when lv.nil? && rv.nil?
li <=> ri
when lv.nil?
-1
when rv.nil?
1
else
lv <=> rv
end
}
# Just sort the data and get an Array in return using Enumerable#sort.
# Non-destructive.
# :nocov:
def sorted_data &block
@data.to_a.sort(&block)
end
# :nocov:
# Like map, but returns a Daru::Vector with the returned values.
def recode dt=nil, &block
return to_enum(:recode) unless block_given?
dup.recode! dt, &block
end
# Destructive version of recode!
def recode! dt=nil, &block
return to_enum(:recode!) unless block_given?
@data.map!(&block).data
@data = cast_vector_to(dt || @dtype)
self
end
# Delete an element if block returns true. Destructive.
def delete_if
return to_enum(:delete_if) unless block_given?
keep_e, keep_i = each_with_index.reject { |n, _i| yield(n) }.transpose
@data = cast_vector_to @dtype, keep_e
@index = Daru::Index.new(keep_i)
update_position_cache
self
end
# Keep an element if block returns true. Destructive.
def keep_if
return to_enum(:keep_if) unless block_given?
delete_if { |val| !yield(val) }
end
# Reports all values that doesn't comply with a condition.
# Returns a hash with the index of data and the invalid data.
def verify
(0...size)
.map { |i| [i, @data[i]] }
.reject { |_i, val| yield(val) }
.to_h
end
# Return an Array with the data splitted by a separator.
# a=Daru::Vector.new(["a,b","c,d","a,b","d"])
# a.splitted
# =>
# [["a","b"],["c","d"],["a","b"],["d"]]
def splitted sep=','
@data.map do |s|
if s.nil?
nil
elsif s.respond_to? :split
s.split sep
else
[s]
end
end
end
# Returns a hash of Vectors, defined by the different values
# defined on the fields
# Example:
#
# a=Daru::Vector.new(["a,b","c,d","a,b"])
# a.split_by_separator
# => {"a"=>#<Daru::Vector:0x7f2dbcc09d88
# @data=[1, 0, 1]>,
# "b"=>#<Daru::Vector:0x7f2dbcc09c48
# @data=[1, 1, 0]>,
# "c"=>#<Daru::Vector:0x7f2dbcc09b08
# @data=[0, 1, 1]>}
#
def split_by_separator sep=','
split_data = splitted sep
split_data
.flatten.uniq.compact.map do |key|
[
key,
Daru::Vector.new(split_data.map { |v| split_value(key, v) })
]
end.to_h
end
def split_by_separator_freq(sep=',')
split_by_separator(sep).map { |k, v|
[k, v.map(&:to_i).inject(:+)]
}.to_h
end
def reset_index!
@index = Daru::Index.new(Array.new(size) { |i| i })
self
end
# Replace all nils in the vector with the value passed as an argument. Destructive.
# See #replace_nils for non-destructive version
#
# == Arguments
#
# * +replacement+ - The value which should replace all nils
def replace_nils! replacement
indexes(*Daru::MISSING_VALUES).each do |idx|
self[idx] = replacement
end
self
end
# Rolling fillna
# replace all Float::NAN and NIL values with the preceeding or following value
#
# @param direction [Symbol] (:forward, :backward) whether replacement value is preceeding or following
#
# @example
# dv = Daru::Vector.new([1, 2, 1, 4, nil, Float::NAN, 3, nil, Float::NAN])
#
# 2.3.3 :068 > dv.rolling_fillna(:forward)
# => #<Daru::Vector(9)>
# 0 1
# 1 2
# 2 1
# 3 4
# 4 4
# 5 4
# 6 3
# 7 3
# 8 3
#
def rolling_fillna!(direction=:forward)
enum = direction == :forward ? index : index.reverse_each
last_valid_value = 0
enum.each do |idx|
if valid_value?(self[idx])
last_valid_value = self[idx]
else
self[idx] = last_valid_value
end
end
self
end
# Non-destructive version of rolling_fillna!
def rolling_fillna(direction=:forward)
dup.rolling_fillna!(direction)
end
# Lags the series by `k` periods.
#
# Lags the series by `k` periods, "shifting" data and inserting `nil`s
# from beginning or end of a vector, while preserving original vector's
# size.
#
# `k` can be positive or negative integer. If `k` is positive, `nil`s
# are inserted at the beginning of the vector, otherwise they are
# inserted at the end.
#
# @param [Integer] k "shift" the series by `k` periods. `k` can be
# positive or negative. (default = 1)
#
# @return [Daru::Vector] a new vector with "shifted" inital values
# and `nil` values inserted. The return vector is the same length
# as the orignal vector.
#
# @example Lag a vector with different periods `k`
#
# ts = Daru::Vector.new(1..5)
# # => [1, 2, 3, 4, 5]
#
# ts.lag # => [nil, 1, 2, 3, 4]
# ts.lag(1) # => [nil, 1, 2, 3, 4]
# ts.lag(2) # => [nil, nil, 1, 2, 3]
# ts.lag(-1) # => [2, 3, 4, 5, nil]
#
def lag k=1
case k
when 0 then dup
when 1...size
copy([nil] * k + data.to_a)
when -size..-1
copy(data.to_a[k.abs...size])
else
copy([])
end
end
def detach_index
Daru::DataFrame.new(
index: @index.to_a,
values: @data.to_a
)
end
# Non-destructive version of #replace_nils!
def replace_nils replacement
dup.replace_nils!(replacement)
end
# number of non-missing elements
def n_valid
size - indexes(*Daru::MISSING_VALUES).size
end
deprecate :n_valid, :count_values, 2016, 10
# Count the number of values specified
# @param values [Array] values to count for
# @return [Integer] the number of times the values mentioned occurs
# @example
# dv = Daru::Vector.new [1, 2, 1, 2, 3, 4, nil, nil]
# dv.count_values nil
# # => 2
def count_values(*values)
positions(*values).size
end
# Returns *true* if an index exists
def has_index? index
@index.include? index
end
# @param keys [Array] can be positions (if by_position is true) or indexes (if by_position if false)
# @return [Daru::Vector]
def get_sub_vector(keys, by_position: true)
return Daru::Vector.new([]) if keys == []
keys = @index.pos(*keys) unless by_position
sub_vect = at(*keys)
sub_vect = Daru::Vector.new([sub_vect]) unless sub_vect.is_a?(Daru::Vector)
sub_vect
end
# @return [Daru::DataFrame] the vector as a single-vector dataframe
def to_df
Daru::DataFrame.new({@name => @data}, name: @name, index: @index)
end
# Convert Vector to a horizontal or vertical Ruby Matrix.
#
# == Arguments
#
# * +axis+ - Specify whether you want a *:horizontal* or a *:vertical* matrix.
def to_matrix axis=:horizontal
if axis == :horizontal
Matrix[to_a]
elsif axis == :vertical
Matrix.columns([to_a])
else
raise ArgumentError, "axis should be either :horizontal or :vertical, not #{axis}"
end
end
# Convert vector to nmatrix object
# @param [Symbol] axis :horizontal or :vertical
# @return [NMatrix] NMatrix object containing all values of the vector
# @example
# dv = Daru::Vector.new [1, 2, 3]
# dv.to_nmatrix
# # =>
# # [
# # [1, 2, 3] ]
def to_nmatrix axis=:horizontal
unless numeric? && !include?(nil)
raise ArgumentError, 'Can not convert to nmatrix'\
'because the vector is numeric'
end
case axis
when :horizontal
NMatrix.new [1, size], to_a
when :vertical
NMatrix.new [size, 1], to_a
else
raise ArgumentError, 'Invalid axis specified. '\
'Valid axis are :horizontal and :vertical'
end
end
# If dtype != gsl, will convert data to GSL::Vector with to_a. Otherwise returns
# the stored GSL::Vector object.
def to_gsl
raise NoMethodError, 'Install gsl-nmatrix for access to this functionality.' unless Daru.has_gsl?
if dtype == :gsl
@data.data
else
GSL::Vector.alloc(reject_values(*Daru::MISSING_VALUES).to_a)
end
end
# Convert to hash (explicit). Hash keys are indexes and values are the correspoding elements
def to_h
@index.map { |index| [index, self[index]] }.to_h
end
# Return an array
def to_a
@data.to_a