Method: ObjectTable#join

Defined in:
lib/object_table.rb

#join(other, key, options = {}) ⇒ Object



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
# File 'lib/object_table.rb', line 88

def join(other, key, options={})
  type = (options[:type] || 'inner')
  key = [key] unless key.is_a?(Array)

  lkeys = key.map{|k| get_column(k).to_a}.transpose
  rkeys = key.map{|k| other[k].to_a}.transpose

  rgroups = rkeys.each_with_index.group_by(&:first)
  rgroups.each{|k, v| rgroups[k] = v.transpose[-1]}

  rindex = rgroups.values_at(*lkeys)
  lindex = lkeys.each_with_index.zip(rindex).flat_map{|(k, i), r| [i] * r.length if r}
  lindex.compact!

  right_cols = other.colnames - key
  left_cols = colnames

  if type == 'left' or type == 'outer'
    lmissing = NArray.to_na(rindex.map{|x| x ? 0 : 1}).where.to_a
    lindex += lmissing
    rindex += [-1] * lmissing.length
  end

  if type == 'right' or type == 'outer'
    left_cols -= key
    rmissing = rgroups.values - rindex
    rmissing.flatten!
    lindex += [-1] * rmissing.length
    rindex += rmissing
  end

  rindex.flatten!.compact!

  lindex = NArray.to_na(lindex)
  rindex = NArray.to_na(rindex)
  lblank = lindex.eq(-1)
  rblank = rindex.eq(-1)

  left = left_cols.map do |k|
    col = get_column(k)
    padding = [nil] * (col.rank - 1)
    col = col[*padding, lindex]
    col[*padding, lblank] = [nil]
    [k, col]
  end

  right = right_cols.map do |k|
    col = other[k]
    padding = [nil] * (col.rank - 1)
    col = col[*padding, rindex]
    col[*padding, rblank] = [nil]
    [k, col]
  end

  keys = []
  if type == 'right' or type == 'outer'
    keys = key.map do |k|
      col = get_column(k)
      padding = [nil] * (col.rank - 1)
      col = col[*padding, lindex]
      col[*padding, lblank] = other[k][*padding, rmissing]
      [k, col]
    end
  end

  self.class.new(keys + left + right)
end