Last active
August 29, 2015 14:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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