Assigning unique id to duplicated rows

dataframe, duplicates, r

Solution

This is the first thing I thought:

Make a new variable which just combines the two columns by pasting their values to strings:

a<-paste0(z$x,z$y) #z is your data.frame

The make this as a factor and combine it to your dataframe:

cbind(z,id=factor(a,labels=1:length(unique(a))))

EDIT: @flodel was concerned about using `paste0`, it's better to use ordinary `paste`, or interaction:

a<-interaction(z,drop=TRUE)
cbind(z,id=factor(a,labels=1:length(unique(a))))

This is assuming that you want to separate `x=ab`, `y=c`, and `x=a`,`y=bc`. If not, then use `paste0`.

Problem

If i have a data frame which looks like this: ``` x y 13 a 14 b 15 c 15 c 14 b ``` and I wanted each group of equal rows to have a unique id, like this: ``` x y id 13 a 1 14 b 2 15 c 3 15 c 3 14 b 2 ``` Is there any easy way of doing this? Thanks

Original source

Related problems