Class: Rust::DataFrame

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(labels_or_data) ⇒ DataFrame

Returns a new instance of DataFrame.



125
126
127
128
129
130
131
132
133
134
135
# File 'lib/rust-core.rb', line 125

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 }
        @data = labels_or_data.clone
    end
end

Class Method Details

.pull_variable(variable) ⇒ Object



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

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

Instance Method Details

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



159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/rust-core.rb', line 159

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



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/rust-core.rb', line 254

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: <<



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/rust-core.rb', line 231

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

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



432
433
434
435
436
# File 'lib/rust-core.rb', line 432

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

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

Raises:

  • (TypeError)


412
413
414
415
416
417
418
419
420
421
422
# File 'lib/rust-core.rb', line 412

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



425
426
427
428
429
# File 'lib/rust-core.rb', line 425

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

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

Raises:

  • (TypeError)


400
401
402
403
404
405
406
407
408
409
# File 'lib/rust-core.rb', line 400

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



439
440
441
# File 'lib/rust-core.rb', line 439

def clone
    DataFrame.new(@data)
end

#column(name) ⇒ Object



174
175
176
# File 'lib/rust-core.rb', line 174

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

#column_namesObject Also known as: colnames



218
219
220
# File 'lib/rust-core.rb', line 218

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

#columnsObject



227
228
229
# File 'lib/rust-core.rb', line 227

def columns
    @labels.size
end

#delete_column(column) ⇒ Object



213
214
215
216
# File 'lib/rust-core.rb', line 213

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

#eachObject



270
271
272
273
274
275
276
# File 'lib/rust-core.rb', line 270

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

#each_with_indexObject



278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/rust-core.rb', line 278

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

#head(n = 10) ⇒ Object



326
327
328
329
330
331
332
# File 'lib/rust-core.rb', line 326

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



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/rust-core.rb', line 305

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

#load_in_r_as(variable_name) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/rust-core.rb', line 291

def 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
    
    Rust._eval_big(command)
end

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

Raises:

  • (TypeError)


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

def merge(other, by, first_alias = "x", second_alias = "y")
    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
    
    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
        end
    end
    
    return result
end

#rename_column!(old_name, new_name) ⇒ Object



178
179
180
181
182
183
184
# File 'lib/rust-core.rb', line 178

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

#row(i) ⇒ Object



137
138
139
140
141
142
143
# File 'lib/rust-core.rb', line 137

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



223
224
225
# File 'lib/rust-core.rb', line 223

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

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



198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/rust-core.rb', line 198

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



190
191
192
193
194
195
196
# File 'lib/rust-core.rb', line 190

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



145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/rust-core.rb', line 145

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

#transform_column!(column) ⇒ Object



186
187
188
# File 'lib/rust-core.rb', line 186

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