【问题标题】:Count of rows with values less than or equal to reference rows值小于或等于参考行的行数
【发布时间】:2015-07-14 21:01:43
【问题描述】:

我有一个表,其中前 10 行是引用。对于非参考行中的每一行(即第 11 行及以后),我想计算参考行(1 到 10)中值小于或等于非参考行中的行数- 参考行。

Row Values
1   1.35
2   0.71
3   1.00
4   0.07
5   0.53
6   0.12
7   0.36
8   2.03
9   3.83
10  1.30
11  2.17
12  1.71
13  1.52
14  1.27
15  0.29
16  0.05
17  0.14

结果如下:

Row Values  Count
1   1.35    
2   0.71    
3   1.00    
4   0.07    
5   0.53    
6   0.12    
7   0.36    
8   2.03    
9   3.83    
10  1.30    
11  2.17    9
12  1.71    8
13  1.52    8
14  1.27    6
15  0.29    2
16  0.05    0
17  0.14    2

【问题讨论】:

    标签: r count row


    【解决方案1】:

    一种选择是使用“NA”创建一个“Count”列,然后用sapply 循环的输出替换元素 11 到最后一个元素。我们循环 'Values' 11:17 并检查有多少参考值小于或等于该值。 (sum(df1$Values[1:10] <= x))

    df1$Count <- NA
    df1$Count[11:nrow(df1)] <- sapply(df1$Values[11:nrow(df1)], 
             function(x) sum(df1$Values[1:10] <= x))
    df1$Count
    #[1] NA NA NA NA NA NA NA NA NA NA  9  8  8  6  2  0  2
    

    或者代替循环,我们也可以使用findInterval

    df1$Count[11:nrow(df1)] <-  findInterval(df1$Values[11:nrow(df1)], 
                             sort(df1$Values[1:10]))
    

    【讨论】:

    • 这正是我想要的。非常感谢。
    【解决方案2】:

    使用 pascal 编程语言(更易于阅读):

    program CompareRowReference(output);
    
    uses 
      sysutils;
    
    const 
      REF_ROW_COUNT = 10;
    
      rowValues: array [1..17] of Double = 
        (1.35, 0.71, 1.00, 0.07, 0.53, 0.12,
         0.36, 2.03, 3.83, 1.30, 2.17, 1.71,
         1.52, 1.27, 0.29, 0.05, 0.14);
    
    var
      ref, nonref: Integer;
      leqCount: Integer; //Less or Equal Counter
    
    begin
      //Print the reference rows
      for ref:=1 to REF_ROW_COUNT do
        writeln(IntToStr(ref)+' '+FloatToStr(rowValues[ref]));
      //Print the nonreference rows with the less-or-equal count
      for nonref:=REF_ROW_COUNT+1 to Length(rowValues) do begin
        leqCount:=0;
        for ref:=1 to REF_ROW_COUNT do
          if(rowValues[ref]<=rowValues[nonref]) then
            Inc(leqCount);
        writeln(IntToStr(nonref)+' '+FloatToStr(rowValues[nonref])+' '+IntToStr(leqCount));
      end;
    end.
    

    您可以在此处查看(或 fork 执行)结果:http://ideone.com/SlMjRR

    【讨论】:

    • 对不起,我没有看到 R 语言标签。请点击@akrun 回答的勾号,接受他的回答。
    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2011-01-25
    • 2016-09-30
    • 2021-09-21
    • 2013-09-02
    相关资源
    最近更新 更多