Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/fselector/util.rb

Overview

add functions to Array class

Instance Method Summary collapse

Instance Method Details

#aveFloat Also known as: mean

average (mean)

Returns:

  • (Float)

    average (mean)



14
15
16
# File 'lib/fselector/util.rb', line 14

def ave
  self.sum / self.size
end

#medianFloat

median

Returns:

  • (Float)

    median



22
23
24
25
26
# File 'lib/fselector/util.rb', line 22

def median
  len = self.size
  sorted = self.sort
  (len % 2 == 1) ? sorted[len/2] : (sorted[len/2-1]+sorted[len/2]).to_f/2
end

#pearson_r(v) ⇒ Float

Pearson's correlation coefficient, two vectors must be of the same length

Parameters:

  • v (Array)

    the second vector

Returns:

  • (Float)

    Pearson's r



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/fselector/util.rb', line 95

def pearson_r(v)
  abort "[#{__FILE__}@#{__LINE__}]: \n"+
        "  two vectors must be of the same length!" if self.size != v.size
  
  sm, vm = self.ave, v.ave
  a, b, c = 0.0, 0.0, 0.0
  
  self.each_with_index do |s, i|
    a += (s-sm)*(v[i]-vm)
    b += (s-sm)**2
    c += (v[i]-vm)**2
  end
  
  if b.zero? or c.zero?
    return 0.0
  else
    return a / Math.sqrt(b) / Math.sqrt(c)
  end
end

#sdFloat

standard deviation

Returns:

  • (Float)

    standard deviation



41
42
43
# File 'lib/fselector/util.rb', line 41

def sd
  Math.sqrt(self.var)
end

#sumFloat

summation

Returns:

  • (Float)

    sum, no need to use .to_f



7
8
9
# File 'lib/fselector/util.rb', line 7

def sum
  self.inject(0.0) { |s, i| s+i }
end

#to_scale(min = 0.0, max = 1.0) ⇒ Array<Float>

scale to [min, max]

Parameters:

  • min (Float) (defaults to: 0.0)

    lower bound

  • max (Float) (defaults to: 1.0)

    upper bound

Returns:

  • (Array<Float>)

    scaled numbers



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/fselector/util.rb', line 51

def to_scale(min=0.0, max=1.0)
  if (min >= max)
    abort "[#{__FILE__}@#{__LINE__}]: \n"+
          "  min must be smaller than max!"
  end
  
  old_min = self.min
  old_max = self.max

  self.collect do |v|
    if old_min == old_max
      max
    else
      min + (v-old_min)*(max-min)/(old_max-old_min)
    end
  end
end

#to_symArray<Symbol>

convert to symbol

Returns:

  • (Array<Symbol>)

    converted symbols



85
86
87
# File 'lib/fselector/util.rb', line 85

def to_sym
  self.collect { |x| x.to_sym }
end

#to_zscoreArray<Float>

convert to z-score

ref: Wikipedia

Returns:

  • (Array<Float>)

    converted z-scores



75
76
77
78
79
80
# File 'lib/fselector/util.rb', line 75

def to_zscore
  ave = self.ave
  sd = self.sd

  return self.collect { |v| (v-ave)/sd }
end

#varFloat

variance

Returns:

  • (Float)

    variance



31
32
33
34
35
36
# File 'lib/fselector/util.rb', line 31

def var
  u = self.ave
  v2 = self.inject(0.0) { |v, i| v+(i-u)*(i-u) }
  
  v2/(self.size-1)
end