计算重复出现次数[R]

时间:2017-08-01 20:44:09

标签: r dataframe

df <- data.frame(name=c('black','black','black','red','red'),
                 type=c('chair','chair','sofa','sofa','sofa'),
                 num=c(4,4,12,4,6))

对于每一行,我想计算&#34;键入&#34;的次数。出现该行的num值,然后创建一个新列。所以对于第一行,&#34;主席&#34;和&#34; num&#34;在数据集中出现两次,因此它被赋值为2.对于第二行,同样的事情。对于第3行,沙发出现一次,值为12。

df
#    name  type num count
# 1 black chair   4     2
# 2 black chair   4     2
# 3 black  sofa  12     1
# 4   red  sofa   4     1
# 5   red  sofa   6     1

2 个答案:

答案 0 :(得分:3)

在基础R中使用ave,你有

df$count <- with(df, ave(num, name, type, num, FUN=length))

获取num的长度,按名称,类型和数字分组。使用with减少输入。

返回

df
   name  type num count
1 black chair   4     2
2 black chair   4     2
3 black  sofa  12     1
4   red  sofa   4     1
5   red  sofa   6     1

答案 1 :(得分:1)

使用let x = {a : function() { // do smth }}; iterateObject(x, (prop) => { prop.a(); }

#define MWR2MM_m 2048  // Bit-length of operands
#define MWR2MM_w 8     // word size
#define MWR2MM_e 257   // number of words per operand

// Type definitions
typedef ap_uint<1> bit_t;             // 1-bit scan
typedef ap_uint< MWR2MM_w > word_t;     // 8-bit words
typedef ap_uint< MWR2MM_m > rsaSize_t;  // m-bit operand size


/*
 * Multiple-word radix 2 montgomery multiplication using carry-propagate adder
 */
void mwr2mm_cpa(rsaSize_t X, rsaSize_t Yin, rsaSize_t Min, rsaSize_t* out)
{
    // extend operands to 2 extra words of 0
    ap_uint<MWR2MM_m + 2*MWR2MM_w> Y = Yin; 
    ap_uint<MWR2MM_m + 2*MWR2MM_w> M = Min;
    ap_uint<MWR2MM_m + 2*MWR2MM_w> S = 0;

    ap_uint<2> C = 0; // two carry bits
    bit_t qi = 0;     // an intermediate result bit

    // Store concatenations in a temporary variable to eliminate HLS compiler warnings about shift count
    ap_uint<MWR2MM_w> temp_concat=0; 

    //  scan X bit-by bit
    for (int i=0; i<MWR2MM_m; i++)
    {
        qi = (X[i]*Y[0]) xor S[0];

        // C gets top two bits of temp_concat, j'th word of S gets bottom 8 bits of temp_concat
        temp_concat = X[i]*Y.range(MWR2MM_w-1,0) + qi*M.range(MWR2MM_w-1,0) + S.range(MWR2MM_w-1,0);
        C = temp_concat.range(9,8);
        S.range(MWR2MM_w-1,0) = temp_concat.range(7,0);

        // scan Y and M word-by word, for each bit of X
        for (int j=1; j<=MWR2MM_e; j++)
        {
            temp_concat = C + X[i]*Y.range(MWR2MM_w*j+(MWR2MM_w-1), MWR2MM_w*j) + qi*M.range(MWR2MM_w*j+(MWR2MM_w-1), MWR2MM_w*j) + S.range(MWR2MM_w*j+(MWR2MM_w-1), MWR2MM_w*j);
            C = temp_concat.range(9,8);
            S.range(MWR2MM_w*j+(MWR2MM_w-1), MWR2MM_w*j) = temp_concat.range(7,0);

            S.range(MWR2MM_w*(j-1)+(MWR2MM_w-1), MWR2MM_w*(j-1)) = (S.bit(MWR2MM_w*j), S.range( MWR2MM_w*(j-1)+(MWR2MM_w-1), MWR2MM_w*(j-1)+1));
        }
        S.range(S.length()-1, S.length()-MWR2MM_w) = 0;
        C=0;
    }

    // if final partial sum is greater than the modulus, bring it back to proper range
    if (S >= M)
        S -= M;

    *out = S;
}