Skip to content

Instantly share code, notes, and snippets.

@MrFlick
Last active August 29, 2015 14:00
Show Gist options
  • Save MrFlick/6052127d54b01393b171 to your computer and use it in GitHub Desktop.
Save MrFlick/6052127d54b01393b171 to your computer and use it in GitHub Desktop.
uniqueify.R: Looks for duplicate values in a vector and assigns them a unique index in the order in which they appear
x<-c(4, 1, 1, 3, 5, 3, 2, 4, 2, 5)
y<-uniqueify(x)
#x has no "primary key", but (x,y) will uniquely identify values (no duplicates)
cbind(x, y)
uniqueify<-function(x) {
ave(rep.int(1,length(X)), x, FUN=seq_along)
}
old.uniqueify<-function(x) {
sort.idx<-order(x);
rev.idx<-order(sort.idx);
cnts<-rle(x[sort.idx]);
ids<-unlist(lapply(cnts$lengths, function(x) {seq(1, x)}))
ids[rev.idx]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment