Skip to content

Instantly share code, notes, and snippets.

@cbare
Last active Jan 11, 2019
Embed
What would you like to do?
A snippet of R code to generate a version 4 (random) UUID.
## Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
## where x is any hexadecimal digit and y is one of 8, 9, A, or B
## e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479
uuid <- function(uppercase=FALSE) {
hex_digits <- c(as.character(0:9), letters[1:6])
hex_digits <- if (uppercase) toupper(hex_digits) else hex_digits
y_digits <- hex_digits[9:12]
paste(
paste0(sample(hex_digits, 8, replace=TRUE), collapse=''),
paste0(sample(hex_digits, 4, replace=TRUE), collapse=''),
paste0('4', paste0(sample(hex_digits, 3, replace=TRUE), collapse=''), collapse=''),
paste0(sample(y_digits,1), paste0(sample(hex_digits, 3, replace=TRUE), collapse=''), collapse=''),
paste0(sample(hex_digits, 12, replace=TRUE), collapse=''),
sep='-')
}
@cbare
Copy link
Author

cbare commented Jul 11, 2013

uuid()
[1] "cb7a4b8a-cab6-4ca9-8c73-d426ffd8dc60"
uuid()
[1] "3dbd5e50-9f58-45d8-a02f-326d22a1310a"
uuid()
[1] "b5441aca-870b-4619-8672-e396a1e5c710"
uuid()
[1] "63e656f5-4b8a-46b0-88f2-c17dda27cff7"
uuid()
[1] "fbb6aba8-7b42-47cf-ab10-2f202d285e27"

@davidcoallier
Copy link

davidcoallier commented Jul 12, 2013

You could use http://www.inside-r.org/packages/cran/dplR/docs/uuid.gen from the dplR package.

require(dplR)

gen <- uuid.gen()
uuid <- gen()

What's nice is you can easily alter the state of the generator with the more_state argument of uuid.gen.

@cbare
Copy link
Author

cbare commented Jul 12, 2013

Thanks to Carl Witthoft for pointing out that my first version was totally broken. Turns out calling sample with replace=TRUE greatly expands the possible UUIDs you might generate! :)

Carl also says, "In general, as I understand it, the value of UUID codes is directly dependent on the quality of the pseudo-random number generator behind them, so I’d recommend reading some R-related literature to make sure “sample” will be good enough for your purposes."

This sounds wise, but I'm not sure if I'm smart enough to follow up on it. It could be that the randomness of these UUIDs is less than ideal.

@heeseonhan
Copy link

heeseonhan commented Jan 11, 2019

Thanks your post.
How can i use it for api service.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment