Class: Simpler::DataFrame

Inherits:
Object
  • Object
show all
Defined in:
lib/simpler/data_frame.rb

Overview

This is an R-centric container for storing data

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash, row_names = nil, col_names = nil) ⇒ DataFrame

takes a hash, where the col_name is the key and the data rows are an array of values. The default ordering of the hash keys will be used, unless overridden with col_names. The row_names can be used to specify the names of the rows (remains nil if no values specified)



30
31
32
33
34
# File 'lib/simpler/data_frame.rb', line 30

def initialize(hash, row_names=nil, col_names=nil)
  @hash = hash
  @row_names = row_names
  @col_names = col_names || @hash.keys
end

Instance Attribute Details

#col_namesObject

this is necessary for



6
7
8
# File 'lib/simpler/data_frame.rb', line 6

def col_names
  @col_names
end

#hashObject

Returns the value of attribute hash.



8
9
10
# File 'lib/simpler/data_frame.rb', line 8

def hash
  @hash
end

#row_namesObject

Returns the value of attribute row_names.



7
8
9
# File 'lib/simpler/data_frame.rb', line 7

def row_names
  @row_names
end

Class Method Details

.from_structs(array) ⇒ Object

takes an array of structs and returns a data frame object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/simpler/data_frame.rb', line 11

def self.from_structs(array)
  names = array.first.members
  lengthwise_arrays = names.map { Array.new(names.size) }
  array.each_with_index do |struct,m|
    struct.values.each_with_index do |val,n|
      lengthwise_arrays[n][m] = val
    end
  end
  hash = {}
  names.zip(lengthwise_arrays) do |name, lengthwise_array|
    hash[name] = lengthwise_array
  end
  self.new(hash)
end

Instance Method Details

#to_r(usefile = nil) ⇒ Object

creates the code to transform the object into R code. If usefile is specified, the dataframe is written as a table and the code generated will read in the table as a data frame.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/simpler/data_frame.rb', line 39

def to_r(usefile=nil)
  if usefile
    raise NotImplementedError, "not implemented just yet"
  else
    # build the vectors
    lines = @col_names.map do |name| 
      val = @hash[name]
      "#{Simpler.varname(val)} <- c(#{val.join(',')})"
    end
    args = @col_names.map do |name|
      "#{name}=#{Simpler.varname(@hash[name])}"
    end
    if @row_names
      varname = Simpler.varname(@row_names)
      lines << "#{varname} <- c(#{@row_names.map {|v| "\"#{v}\""}.join(',')})"
      args.push("row.names=#{varname}")
    end
    lines << "#{Simpler.varname(self)} <- data.frame(#{args.join(', ')})"
    lines.join("\n") << "\n"
  end
end