How to Generate 6 Digit Unique Random Number R?

Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in R?

While R doesn’t have a built-in function specifically for generating random numbers within a specific range like 6 digits, you can achieve this using different approaches:

Using `sample` and ensuring 6 digits.

generate_six_digit_number <- function() {

# Generate random digits between 0 and 9
digits <- sample(0:9, 6, replace = TRUE)

# Combine the digits into a single string
number_string <- paste(digits, collapse = "")

# Convert the string to an integer
number <- as.integer(number_string)
return(number)
}

# Generate and print a 6-digit random number
number <- generate_six_digit_number()
cat("Generated 6-digit number: ", number, "\n")

Explanation.

1. The `generate_six_digit_number` function uses `sample(0:9, 6, replace = TRUE)` to sample 6 random digits (0-9) with replacement, ensuring all digits have an equal chance of being chosen.
2. `paste(digits, collapse = “”)` joins the individual digits into a single string representation.
3. `as.integer(number_string)` converts the string back to an integer.

Using `floor` and `runif`.

generate_six_digit_number <- function() {

# Generate a random number between 0 and 1 million (excluding 1 million)
random_number <- runif(1, min = 0, max = 1000000)

# Floor the number to remove decimal part and ensure it's within the range
number <- floor(random_number)
return(number)
}

# Generate and print a 6-digit random number
number <- generate_six_digit_number()
cat("Generated 6-digit number: ", number, "\n")

Explanation:-

1. The `generate_six_digit_number` function uses `runif(1, min = 0, max = 1000000)` to generate a single random number between 0 (inclusive) and 1 million (exclusive).
2. `floor(random_number)` removes the decimal part of the random number, effectively converting it to an integer.
3. Since the original range was 0 to 999999.999999 (excluding 1 million), the result will always be within the desired range of 0 to 999999.