How to Generate a UUID in R
The standard way to generate a UUID in R is the uuid package from CRAN — base R has no built-in UUID generator, so install the package once, then call UUIDgenerate() to produce a random (v4) identifier as a plain character string. The rust uuid generator reference explains how to generate v4 and v7 UUIDs with Rust's ownership-safe uuid crate.
install.packages("uuid")
library(uuid)
my_uuid <- UUIDgenerate()
print(my_uuid)
# [1] "550e8400-e29b-41d4-a716-446655440000"
Explanation
install.packages("uuid")pulls the package from CRAN — this is a one-time install per machine, not something you repeat in every script.library(uuid)loads the package into your current R session soUUIDgenerate()becomes available.UUIDgenerate()returns a random (version 4) UUID as a plain character string, with no special wrapper class involved.print(my_uuid)shows R's default character vector display,[1] "...", since the value is just a string.
Validate a UUID String in R
The uuid package has no dedicated parser, so the simplest way to check whether a string is a valid UUID in R is a regular expression match against the canonical 8-4-4-4-12 hex pattern using grepl(). The c++ uuid reference explains how to generate and parse UUIDs in C++ with proper formatting.
my_uuid <- UUIDgenerate()
is_valid <- grepl(
"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
my_uuid,
ignore.case = TRUE
)
print(is_valid)
# [1] TRUE
Explanation
grepl()returnsTRUEorFALSEfor each string tested against the pattern, so it works on a single value or an entire vector of strings at once.- The regex enforces the 8-4-4-4-12 hyphenated hex groups that every UUID string uses, regardless of version.
ignore.case = TRUEaccepts UUIDs written in either uppercase or lowercase hex digits, since both are valid.- This checks the string's shape only — it confirms the format looks like a UUID, not that it was generated correctly.
Other Options for Generating UUIDs in R
UUIDgenerate()'s default output covers most use cases, but the use.time argument switches to a time-based UUID, and the n argument generates several UUIDs in a single call — handy when you need to stamp every row of a data frame at once.
library(uuid)
# Time-based UUID instead of pure random
time_based <- UUIDgenerate(use.time = TRUE)
# Generate 10 UUIDs in a single call
batch_ids <- UUIDgenerate(n = 10)
Explanation
UUIDgenerate(use.time = TRUE)embeds the current timestamp instead of relying on pure randomness, producing IDs that sort roughly by creation order.UUIDgenerate(n = 10)returns a character vector of 10 independently generated UUIDs in one call, avoiding an explicit loop.- Combine
nwithuse.timeto generate a batch of timestamp-ordered IDs — useful for stamping every row of a data frame at once. - Neither argument requires an extra package — both ship with the base
uuidpackage install.