Class: Rust::DataFrame

Inherits:
RustDatatype show all
Defined in:
lib/rust/core/types/dataframe.rb

Overview

Mirror of the data-frame type in R.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from RustDatatype

#r_hash, #r_mirror, #r_mirror_to

Constructor Details

#initialize(labels_or_data) ⇒ DataFrame

Creates a new data-frame. labels_or_data can be either:

  • an Array of column names (creates an empty data-frame)

  • a Hash with column names as keys and values as values



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rust/core/types/dataframe.rb', line 33

def initialize(labels_or_data)
    @data = {}
    
    if labels_or_data.is_a? Array
        @labels = labels_or_data.map { |l| l.to_s }
        @labels.each { |label| @data[label] = [] }
    elsif labels_or_data.is_a? Hash
        @labels = labels_or_data.keys.map { |l| l.to_s }
        
        labels_or_data.each do |key, value|
            @data[key.to_s] = value.clone
        end
    end
end

Class Method Details

.can_pull?(type, klass) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/rust/core/types/dataframe.rb', line 10

def self.can_pull?(type, klass)
    return [klass].flatten.include?("data.frame")
end

.pull_priorityObject



14
15
16
# File 'lib/rust/core/types/dataframe.rb', line 14

def self.pull_priority
    1
end

.pull_variable(variable, type, klass) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/rust/core/types/dataframe.rb', line 18

def self.pull_variable(variable, type, klass)
    hash = {}
    colnames = Rust["colnames(#{variable})"]
    colnames.each do |col|
        hash[col] = Rust["#{variable}$\"#{col}\""]
    end
    return DataFrame.new(hash)
end

Instance Method Details

#[](rows, cols = nil) ⇒ Object

Returns a copy of the data-frame containing only the specified rows and/or cols. If rows and/or cols are nil, all the rows/columns are returned.



91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/rust/core/types/dataframe.rb', line 91

def [](rows, cols=nil)
    raise "You must specify either rows or columns to select" if !rows && !cols
    result = self
    if rows && (rows.is_a?(Range) || rows.is_a?(Array))
        result = result.select_rows { |row, i| rows.include?(i) }
    end
    
    if cols && cols.is_a?(Array)
        cols = cols.map { |c| c.to_s }
        result = result.select_columns(cols)
    end
    
    return result
end

#add_column(name, values = nil) ⇒ Object

Adds a column named name with the given values (array). The size of values must match the number of rows of this data-frame. As an alternative, it can be passed a block which returns, for a given row, the value to assign for the new column.



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/rust/core/types/dataframe.rb', line 286

def add_column(name, values=nil)
    raise "Column already exists" if @labels.include?(name)
    raise "Values or block required" if !values && !block_given?
    raise "Number of values not matching" if values && values.size != self.rows
    
    @labels << name
    if values
        @data[name] = values.clone
    else
        @data[name] = []
        self.each_with_index do |row, i|
            @data[name][i] = yield row
        end
    end
end

#add_row(row) ⇒ Object Also known as: <<

Adds the given row to the data-frame. row can be either:

  • An Array of values for all the columns (in the order of #column_names);

  • A Hash containing associations between column names and value to be set.



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/rust/core/types/dataframe.rb', line 258

def add_row(row)
    if row.is_a?(Array)
        raise "Expected an array of size #{@data.size}" unless row.size == @data.size
        
        @labels.each_with_index do |label, i|
            @data[label] << row[i]
        end
        
        return true
    elsif row.is_a?(Hash)
        raise "Expected a hash with the following keys: #{@data.keys}" unless row.keys.map { |l| l.to_s }.sort == @data.keys.sort
        
        row.each do |key, value|
            @data[key.to_s] << value
        end
        
        return true
    else
        raise TypeError, "Expected an Array or a Hash"
    end
end

#aggregate(by, **aggregators) ⇒ Object

Aggregate the value in groups depending on the by column (String). A block must be passed to specify how to aggregate the columns. Aggregators for specific columns can be specified as optional arguments in which the name of the argument represents the column name and the value contains a block for aggregating the specific column. Both the default and the specialized blocks must take as argument an array of values and must return a scalar value.

Raises:

  • (TypeError)


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
# File 'lib/rust/core/types/dataframe.rb', line 557

def aggregate(by, **aggregators)
    raise TypeError, "Expected a string" unless by.is_a?(String)
    raise TypeError, "All the aggregators should be procs" unless aggregators.values.all? { |v| v.is_a?(Proc) }
    raise "Expected a block for default aggregator" unless block_given?
    
    aggregators = aggregators.map { |label, callable| [label.to_s, callable] }.to_h
    
    sorted = self.sort_by(by)
    
    current_value = nil
    partials = []
    partial = nil
    sorted.column(by).each_with_index do |value, index|
        if current_value != value
            current_value = value
            partials << partial if partial
            partial = Rust::DataFrame.new(self.column_names)
        end
        partial << sorted.fast_row(index)
    end
    partials << partial
    
    result = Rust::DataFrame.new(self.column_names)
    partials.each do |partial|
        aggregated_row = {}
        aggregated_row[by] = partial.column(by)[0]
        (self.column_names - [by]).each do |column|
            if aggregators[column]
                aggregated_row[column] = aggregators[column].call(partial.column(column))
            else
                aggregated_row[column] = yield partial.column(column)
            end
        end
        
        result << aggregated_row
    end
    
    return result
end

#bind_columns(dataframe) ⇒ Object Also known as: cbind

Returns a copy of this dataframe and adds all the columns in dataframe to it. The number of rows must match.



678
679
680
681
682
# File 'lib/rust/core/types/dataframe.rb', line 678

def bind_columns(dataframe)
    result = self.clone
    result.bind_columns!(dataframe)
    return result
end

#bind_columns!(dataframe) ⇒ Object Also known as: cbind!

Adds all the columns in dataframe to this data-frame. The number of rows must match.

Raises:

  • (TypeError)


652
653
654
655
656
657
658
659
660
661
662
# File 'lib/rust/core/types/dataframe.rb', line 652

def bind_columns!(dataframe)
    raise TypeError, "DataFrame expected" unless dataframe.is_a?(DataFrame)
    raise "The number of rows are not compatible" if self.rows != dataframe.rows
    raise "The dataset would override some columns" if (self.column_names & dataframe.column_names).size > 0
    
    dataframe.column_names.each do |column_name|
        self.add_column(column_name, dataframe.column(column_name))
    end
    
    return true
end

#bind_rows(dataframe) ⇒ Object Also known as: rbind

Returns a copy of this dataframe and adds all the rows in dataframe to it. The column names must match.



668
669
670
671
672
# File 'lib/rust/core/types/dataframe.rb', line 668

def bind_rows(dataframe)
    result = self.clone
    result.bind_rows!(dataframe)
    return result
end

#bind_rows!(dataframe) ⇒ Object Also known as: rbind!

Adds all the rows in dataframe to this data-frame. The column names must match.

Raises:

  • (TypeError)


637
638
639
640
641
642
643
644
645
646
# File 'lib/rust/core/types/dataframe.rb', line 637

def bind_rows!(dataframe)
    raise TypeError, "DataFrame expected" unless dataframe.is_a?(DataFrame)
    raise "The columns are not compatible: #{self.column_names - dataframe.column_names} - #{dataframe.column_names - self.column_names}" unless (self.column_names & dataframe.column_names).size == self.columns
    
    dataframe.each do |row|
        self << row
    end
    
    return true
end

#cloneObject

Returns a copy of this data-frame.



688
689
690
# File 'lib/rust/core/types/dataframe.rb', line 688

def clone
    DataFrame.new(@data)
end

#column(name) ⇒ Object Also known as: |

Return the column named name.



109
110
111
# File 'lib/rust/core/types/dataframe.rb', line 109

def column(name)
    return @data[name]
end

#column_namesObject Also known as: colnames

Return the names of the columns.



234
235
236
# File 'lib/rust/core/types/dataframe.rb', line 234

def column_names
    return @labels.map { |k| k.to_s }
end

#columnsObject

Returns the number of columns



249
250
251
# File 'lib/rust/core/types/dataframe.rb', line 249

def columns
    @labels.size
end

#delete_column(column) ⇒ Object

Deletes the column named column.



183
184
185
186
# File 'lib/rust/core/types/dataframe.rb', line 183

def delete_column(column)
    @labels.delete(column)
    @data.delete(column)
end

#delete_row(i) ⇒ Object

Deletes the i-th row.



191
192
193
194
195
# File 'lib/rust/core/types/dataframe.rb', line 191

def delete_row(i)
    @data.each do |label, column|
        column.delete_at(i)
    end
end

#directly_load_in_r_as(variable_name) ⇒ Object



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
# File 'lib/rust/core/types/dataframe.rb', line 375

def directly_load_in_r_as(variable_name)
    command = []
                
    command << "#{variable_name} <- data.frame()"
    row_index = 1
    self.each do |row|
        command << "#{variable_name}[#{row_index.to_R}, #{row.keys.to_R}] <- #{row.values.to_R}"
        
        row_index += 1
    end
    
    self.column_names.each do |name|
        column = self.column(name)
        
        if column.is_a?(Factor)
            command << "#{variable_name}[,#{name.to_R}] <- factor(#{variable_name}[,#{name.to_R}], labels=#{column.levels.to_R})"
        end
    end
    
    Rust._eval_big(command)
    
    tempfile.unlink
    
    return true
end

#eachObject

Yields each row as a Hash containing column names as keys and values as values.



305
306
307
308
309
310
311
# File 'lib/rust/core/types/dataframe.rb', line 305

def each
    self.each_with_index do |element, i|
        yield element
    end
    
    return self
end

#each_with_indexObject

Yields each row as a Hash containing column names as keys and values as values and the row index.



328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/rust/core/types/dataframe.rb', line 328

def each_with_index
    for i in 0...self.rows
        element = {}
        @labels.each do |label|
            element[label] = @data[label][i]
        end
        
        yield element, i
    end
    
    return self
end

#fast_eachObject

Yields each row as a Hash containing column names as keys and values as values. Faster alternative to #each.



317
318
319
320
321
322
323
# File 'lib/rust/core/types/dataframe.rb', line 317

def fast_each
    self.fast_each_with_index do |element, i|
        yield element
    end
    
    return self
end

#fast_each_with_indexObject

Yields each row as a Hash containing column names as keys and values as values and the row index. Faster alternative to #each_with_index.



345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/rust/core/types/dataframe.rb', line 345

def fast_each_with_index
    for i in 0...self.rows
        element = []
        @labels.each do |label|
            element << @data[label][i]
        end
        
        yield element, i
    end
    
    return self
end

#fast_row(i) ⇒ Object

Returns the i-th row of the data-frame. Faster (but harder to interpret) alternative to #row.



62
63
64
65
66
67
68
# File 'lib/rust/core/types/dataframe.rb', line 62

def fast_row(i)
    if i < 0 || i >= self.rows
        return nil
    else
        return @labels.map { |label| @data[label][i] }
    end
end

#has_row?Boolean

Returns true if the function given in the block returns true for any of the rows in this data-frame.

Returns:

  • (Boolean)


154
155
156
157
158
159
# File 'lib/rust/core/types/dataframe.rb', line 154

def has_row?
    self.each_with_index do |row, i|
        return true if yield row, i
    end
    return false
end

#head(n = 10) ⇒ Object

Returns a copy of the data-frame containing only the first n rows.



425
426
427
428
429
430
431
# File 'lib/rust/core/types/dataframe.rb', line 425

def head(n=10)
    result = DataFrame.new(self.column_names)
    self.each_with_index do |row, i|
        result << row if i < n
    end
    return result
end

#inspectObject



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/rust/core/types/dataframe.rb', line 401

def inspect
    separator = " | "
    col_widths = self.column_names.map { |colname| [colname, ([colname.length] + @data[colname].map { |e| e.inspect.length }).max] }.to_h
    col_widths[:rowscol] = (self.rows - 1).inspect.length + 3
    
    result = ""
    result << "-" * (col_widths.values.sum + ((col_widths.size - 1) * separator.length)) + "\n"
    result << (" " * col_widths[:rowscol]) + self.column_names.map { |colname| (" " * (col_widths[colname] - colname.length)) + colname }.join(separator) + "\n"
    result << "-" * (col_widths.values.sum + ((col_widths.size - 1) * separator.length)) + "\n"
    self.each_with_index do |row, i|
        index_part = "[" + (" " * (col_widths[:rowscol] - i.inspect.length - 3)) + "#{i}] "
        row_part   = row.map { |colname, value| (" " * (col_widths[colname] - value.inspect.length)) + value.inspect }.join(separator)
        
        result << index_part + row_part + "\n"
    end
    
    result << "-" * (col_widths.values.sum + ((col_widths.size - 1) * separator.length))
    
    return result
end

#left_merge(other, by, first_alias, second_alias, **options) ⇒ Object

Merges this data-frame with other in terms of the by column(s) (Array or String). Keeps all the rows in this data frame. first_alias and second_alias allow to specify the prefix that should be used for the columns not in by for this and the other data-frame, respectively.



438
439
440
441
442
# File 'lib/rust/core/types/dataframe.rb', line 438

def left_merge(other, by, first_alias, second_alias, **options)
    options[:keep_right] = true
    options[:keep_left]  = false
    return other.merge(self, by, first_alias, second_alias, **options)
end

#load_in_r_as(variable_name) ⇒ Object



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/rust/core/types/dataframe.rb', line 358

def load_in_r_as(variable_name)
    tempfile = Tempfile.new('rust.dfport')
    tempfile.close
    
    Rust::CSV.write(tempfile.path, self)
    Rust._eval("#{variable_name} <- read.csv(\"#{tempfile.path}\", header=T)")
    
    if Rust.debug?
        FileUtils.cp(tempfile.path, tempfile.path + ".debug.csv")
        puts "Debug CSV port file available at: #{tempfile.path + ".debug.csv"}"
    end
    
    tempfile.unlink
    
    return true
end

#merge(other, by, first_alias = "x", second_alias = "y", **options) ⇒ Object

Merges this data-frame with other in terms of the by column(s) (Array or String). first_alias and second_alias allow to specify the prefix that should be used for the columns not in by for this and the other data-frame, respectively.

Raises:

  • (TypeError)


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
# File 'lib/rust/core/types/dataframe.rb', line 460

def merge(other, by, first_alias = "x", second_alias = "y", **options)
    raise TypeError, "Expected Rust::DataFrame" unless other.is_a?(DataFrame)
    raise TypeError, "Expected list of strings" if !by.is_a?(Array) || !by.all? { |e| e.is_a?(String) }
    raise "This dataset should have all the columns in #{by}" unless (by & self.column_names).size == by.size
    raise "The passed dataset should have all the columns in #{by}" unless (by & other.column_names).size == by.size
    raise "Either keep_right or keep_left should be provided as options, not both" if options[:keep_right] && options[:keep_left]
    
    if first_alias == second_alias
        if first_alias == ""
            my_columns = self.column_names - by
            other_columns = other.column_names - by
            intersection = my_columns & other_columns
            raise "Cannot merge because the following columns would overlap: #{intersection}" if intersection.size > 0
        else
            raise "The aliases can not have the same value"
        end
    end
    
    my_keys = {}
    self.each_with_index do |row, i|
        key = []
        by.each do |colname|
            key << row[colname]
        end
        
        my_keys[key] = i
    end
    
    merged_column_self  = (self.column_names - by)
    merged_column_other = (other.column_names - by)
    
    first_alias =  first_alias + "."     if first_alias.length > 0
    second_alias = second_alias + "."    if second_alias.length > 0
    
    merged_columns = merged_column_self.map { |colname| "#{first_alias}#{colname}" } + merged_column_other.map { |colname| "#{second_alias}#{colname}" }
    columns = by + merged_columns
    result = DataFrame.new(columns)
    other.each do |other_row|
        key = []
        by.each do |colname|
            key << other_row[colname]
        end
        
        my_row_index = my_keys[key]
        if my_row_index
            my_row = self.row(my_row_index)
            
            to_add = {}
            by.each do |colname|
                to_add[colname] = my_row[colname]
            end
            
            merged_column_self.each do |colname|
                to_add["#{first_alias}#{colname}"] = my_row[colname]
            end
            
            merged_column_other.each do |colname|
                to_add["#{second_alias}#{colname}"] = other_row[colname]
            end
            
            result << to_add
            
        elsif options[:keep_right]
            to_add = {}
            
            by.each do |colname|
                to_add[colname] = other_row[colname]
            end
            
            merged_column_self.each do |colname|
                to_add["#{first_alias}#{colname}"] = nil
            end
            
            merged_column_other.each do |colname|
                to_add["#{second_alias}#{colname}"] = other_row[colname]
            end
            
            result << to_add
            
        elsif options[:keep_left]
            options[:keep_left]  = false
            options[:keep_right] = true
            return other.merge(self, by, first_alias, second_alias, **options)
        end
    end
    
    return result
end

#rename_column!(old_name, new_name) ⇒ Object

Renames the column named old_name in new_name.



117
118
119
120
121
122
123
# File 'lib/rust/core/types/dataframe.rb', line 117

def rename_column!(old_name, new_name)
    raise "This DataFrame does not contain a column named #{old_name}" unless @labels.include?(old_name)
    raise "This DataFrame already contains a column named #{new_name}" if @labels.include?(new_name)
    
    @data[new_name.to_s] = @data.delete(old_name)
    @labels[@labels.index(old_name)] = new_name
end

#right_merge(other, by, first_alias, second_alias, **options) ⇒ Object

Merges this data-frame with other in terms of the by column(s) (Array or String). Keeps all the rows in the other data frame. first_alias and second_alias allow to specify the prefix that should be used for the columns not in by for this and the other data-frame, respectively.



449
450
451
452
453
# File 'lib/rust/core/types/dataframe.rb', line 449

def right_merge(other, by, first_alias, second_alias, **options)
    options[:keep_right] = true
    options[:keep_left]  = false
    return self.merge(other, by, first_alias, second_alias, **options)
end

#row(i) ⇒ Object

Returns the i-th row of the data-frame



51
52
53
54
55
56
57
# File 'lib/rust/core/types/dataframe.rb', line 51

def row(i)
    if i < 0 || i >= self.rows
        return nil
    else
        return @data.map { |label, values| [label, values[i]] }.to_h
    end
end

#rowsObject

Returns the number of rows.



242
243
244
# File 'lib/rust/core/types/dataframe.rb', line 242

def rows
    @data.values[0].size
end

#select_columns(cols = nil) ⇒ Object Also known as: select_cols

Returns a copy of the data-frame with only the columns in cols. As an alternative, a block can be used (only the columns for which the function returns true are kept).



165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/rust/core/types/dataframe.rb', line 165

def select_columns(cols=nil)
    raise "You must specify either the columns you want to select or a selection block" if !cols && !block_given?
    
    result = self.clone
    @labels.each do |label|
        if cols
            result.delete_column(label) unless cols.include?(label)
        else
            result.delete_column(label) unless yield label
        end
    end
    return result
end

#select_rowsObject

Returns a copy data-frame with only the rows for which the function given in the block returns true. Example: df = Rust::DataFrame.new([1,2,3], b: [‘a’,‘b’,‘c’]) df2 = df.select_rows { |r| r.even? } df2|“b” # => [‘b’]



143
144
145
146
147
148
149
# File 'lib/rust/core/types/dataframe.rb', line 143

def select_rows
    result = DataFrame.new(self.column_names)
    self.each_with_index do |row, i|
        result << row if yield row, i
    end
    return result
end

#shuffle(*args) ⇒ Object

Shuffles the rows in the data-frame. The arguments are passed to the Array#shuffle method.



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/rust/core/types/dataframe.rb', line 73

def shuffle(*args)
    result = DataFrame.new(@labels)
    
    buffer = []
    self.each do |row|
        buffer << row
    end
    buffer.shuffle!(*args).each do |row|
        result << row
    end
    
    return result
end

#sort_by(column) ⇒ Object

Returns a copy of this data-frame in which the rows are sorted by the values of the by column.



600
601
602
603
604
# File 'lib/rust/core/types/dataframe.rb', line 600

def sort_by(column)
    result = self.clone
    result.sort_by!(column)
    return result
end

#sort_by!(by) ⇒ Object

Sorts the rows of this data-frame by the values of the by column.



609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/rust/core/types/dataframe.rb', line 609

def sort_by!(by)
    copy = @data[by].clone
    copy.sort!
    
    indices = []
    @data[by].each_with_index do |value, i|
        index = copy.index(value)
        indices << index
        
        copy[index] = NilClass
    end
                
    (self.column_names - [by]).each do |column_name|
        sorted = []
        column = self.column(column_name)
        column_i = 0
        indices.each do |i|
            sorted[i] = column[column_i]
            column_i += 1
        end
        @data[column_name] = sorted
    end
    @data[by].sort!
end

#transform_column!(column) ⇒ Object

Functionally transforms the column named column by applying the function given as a block. Example: df = Rust::DataFrame.new([1,2,3], b: [3,4,5]) df.transform_column!(“a”) { |v| v + 1 } df|“a” # => [2, 3, 4]



132
133
134
# File 'lib/rust/core/types/dataframe.rb', line 132

def transform_column!(column)
    @data[column].map! { |e| yield e }
end

#uniq_by(by) ⇒ Object

Returns a data-frame in which the rows are unique in terms of all the given columns named by.



200
201
202
203
204
# File 'lib/rust/core/types/dataframe.rb', line 200

def uniq_by(by)
    result = self.clone
    result.uniq_by!(by)
    return result
end

#uniq_by!(by) ⇒ Object

Makes sure that in this data-frame the rows are unique in terms of all the given columns named by.



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/rust/core/types/dataframe.rb', line 209

def uniq_by!(by)
    my_keys = {}
    to_delete = []
    self.each_with_index do |row, i|
        key = []
        by.each do |colname|
            key << row[colname]
        end
        unless my_keys[key]
            my_keys[key] = i
        else
            to_delete << (i-to_delete.size)
        end
    end
    
    to_delete.each do |i|
        self.delete_row(i)
    end
    
    return self
end