Search code examples
rdataframeunique

Count unique values in R and display in column


I have this dataframe, and I would like to count the unique values in column A and display them in Column D

So the if else function should look at column A and ad 1 for each new unique user

> DF_Have <- data.frame(A=c(1,2,2,3,3), B=1:5*10, C=1:5*100)
> DF_Have
   A  B   C
1: 1 10 100
2: 2 20 200
3: 2 30 300
4: 3 40 400
5: 3 50 500


> DF_Want
   A  B   C   D
1: 1 10 100   1
2: 2 20 200   2
3: 2 30 300   2
4: 3 40 400   3
5: 3 50 500   3

Solution

  • library(data.table)
    DF_Have$D <- rleid(DF_Have$A)
    DF_Have
    #  A  B   C D
    #1 1 10 100 1
    #2 2 20 200 2
    #3 2 30 300 2
    #4 3 40 400 3
    #5 3 50 500 3
    

    another option without need of any external package is( provided DF_Have$A is ordered)

    DF_Have$D <- cumsum(!duplicated(DF_Have$A))