KhalidN
KhalidN

Reputation: 405

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

Upvotes: 1

Views: 296

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 389235

We can use base R match

DF_Have$D <- match(DF_Have$A, unique(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

Upvotes: 2

joel.wilson
joel.wilson

Reputation: 8413

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))

Upvotes: 3

akrun
akrun

Reputation: 887841

Perhaps this helps

library(data.table)
setDT(DF_Have)[, D:= rleid(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

Or using dplyr

library(dplyr)
DF_Have %>%
     mutate(D = cumsum(c(TRUE, A[-1]!= A[-length(A)])))

Upvotes: 2

Related Questions