counting occurrences in column and create variable in R

后端 未结 3 787
执念已碎
执念已碎 2020-12-28 10:20

I am new on R and I have a data.frame , called \"CT\", containing a column called \"ID\" containing several hundreds of different identification numbers (these are patients)

3条回答
  •  清歌不尽
    2020-12-28 10:59

    You were almost there! rle will work very nicely, you just need to sort your table on ID before computing rle:

    CT <- data.frame( value = runif(10) , id = sample(5,10,repl=T) )
    
    #  sort on ID when calculating rle
    Count <- rle( sort( CT$id ) )
    
    #  match values
    CT$Count <- Count[[1]][ match( CT$id , Count[[2]] ) ]
    CT
    #       value id Count
    #1  0.94282600  1     4
    #2  0.12170165  2     2
    #3  0.04143461  1     4
    #4  0.76334609  3     2
    #5  0.87320740  4     1
    #6  0.89766749  1     4
    #7  0.16539820  1     4
    #8  0.98521044  5     1
    #9  0.70609853  3     2
    #10 0.75134208  2     2
    

提交回复
热议问题