从百分比中获取数组的一部分

时间:2015-05-28 02:09:15

标签: arrays ruby

我真的无法绕过它。
所以我想做的是从阵列中获取4组,如下所示:

  • 结果[0]< - 前10%
  • 结果[1]< - 遵循20%
  • 结果[2]< - 以下30%
  • 结果[3]< - 遵循40%

这是我的代码:

Data <- Data[order(Data$Name, as.Date(Data$Date, "%m/%d/%Y")),]

tapply(log10(Data$Value_1), Data$Name, function(x) head(x,1) - tail(x,1) >= 2)
#    A     B     C     D 
#FALSE FALSE FALSE  TRUE 

aggregate(log10(Data["Value_1"]), Data["Name"], FUN=function(x) head(x,1) - tail(x,1) >= 2)
#  Name Value_1
#1    A   FALSE
#2    B   FALSE
#3    C   FALSE
#4    D    TRUE

有没有更好的方法(和功能)来做到这一点?

2 个答案:

答案 0 :(得分:1)

你可以这样做。

<强>代码

def partition_array(arr, cum_breaks)
  n = arr.size
  cum_breaks.map { |f| (n*f).to_i }.each_cons(2).map do|f,l|
    if f.zero?
      if l.zero?
        []
      else
        arr[0..l-1]
      end
    else
      arr[f..l-1]
    end
  end
end

<强>实施例

cum_breaks = [0.0, 0.1, 0.3, 0.6, 1.0]

n = 30
arr = Array.new(n) { |i| i }
  #=> [0, 1, 2, 3,..., 28, 31] 
a = partition_array(arr, cum_breaks)
  #=> [[ 0,  1,  2],
  #    [ 3,  4,  5,  6,  7,  8],
  #    [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
  #    [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]] 
a.map { |e| [e.size, (e.size/arr.size.to_f).round(3)] }
  #=> [[3, 0.1], [6, 0.2], [9, 0.3], [12, 0.4]]

n = 37
arr = Array.new(n) { |i| i }
  #=> [0, 1, 2, 3,..., 35, 36] 
a = partition_array(arr, cum_breaks)
  #=> [[ 0,  1,  2],
  #    [ 3,  4,  5,  6,  7,  8,  9, 10],
  #    [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
  #    [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]] 
a.map { |e| [e.size, (e.size/arr.size.to_f).round(3)] }
  #=> [[3, 0.081], [8, 0.216], [11, 0.297], [15, 0.405]]

n = 9
arr = Array.new(n) { |i| i }
  #=> [0, 1, 2, 3, 4, 5, 6, 7, 8] 
a = partition_array(arr, cum_breaks)
  #=> [[], [0, 1], [2, 3, 4], [5, 6, 7, 8]]
a.map { |e| [e.size, (e.size/arr.size.to_f).round(3)] }
  #=> [[0, 0.0], [2, 0.222], [3, 0.333], [4, 0.444]] 

答案 1 :(得分:0)

我使用了一种不同的技术,对于像我这样的Ruby初学者来说,阅读和理解起来有点简单。

a = Array 0..199
original_length = a.length

def percents_elements(array, array_length, percent)
  p_length = (array_length * percent / 100.0).round
  a = array.slice!(0, p_length)
end

results = [
  percents_elements(a, original_length, 10),
  percents_elements(a, original_length, 20),
  percents_elements(a, original_length, 30),
  percents_elements(a, original_length, 40)
]
puts "Result is #{results.flatten.count} entries long"
print results