How to Generate Random Numbers in RStudio

How-to basics · Updated November 25, 2026

Generating random numbers in RStudio is a core task for simulations, sampling, bootstrapping, and Monte Carlo experiments. R provides a family of simple functions—runif(), rnorm(), sample(), and a few others—that let you create random values from different probability distributions. This guide walks you through the exact steps, including setting a random seed for reproducibility, and covers common pitfalls and troubleshooting.

What You’ll Need

  • RStudio installed (any recent version, on Windows, Mac, or Linux).
  • Basic familiarity with the R console or an R script file.
  • No additional packages are required—all functions used are base R.

Step-by-Step

  1. Open RStudio and create a new script (optional). Click File > New File > R Script (or use Ctrl+Shift+N on Windows/Linux, Cmd+Shift+N on Mac). You can also type directly in the Console, but a script makes it easier to edit and rerun.
  2. Generate a single random number from a uniform distribution (0 to 1). Type runif(1) and press Ctrl+Enter (or Cmd+Enter on Mac) if in a script. The output is one decimal between 0 and 1. For example, you might see [1] 0.3723.
  3. Generate a vector of multiple uniform random numbers. Use runif(5) to get five values between 0 and 1. To change the range, add arguments: runif(5, min = 10, max = 20) yields five numbers between 10 and 20.
  4. Generate random numbers from a normal (Gaussian) distribution. Use rnorm(3) for three values with mean 0 and standard deviation 1. Specify parameters: rnorm(10, mean = 100, sd = 15) gives ten numbers centered at 100 with a spread of 15.
  5. Sample random integers (discrete uniform). Use sample(1:10, size = 4) to pick four distinct integers from 1 to 10. To allow repeats, add replace = TRUE: sample(1:6, size = 5, replace = TRUE) simulates rolling a die five times.
  6. Sample from a character vector or custom set. For example, sample(c("red", "green", "blue"), size = 2) picks two colors without replacement. Add replace = TRUE if you want duplicates allowed.
  7. Generate random numbers from other distributions. Use rpois(5, lambda = 3) for Poisson, rexp(5, rate = 1) for exponential, rbinom(5, size = 10, prob = 0.5) for binomial, and rt(5, df = 10) for t-distribution. The pattern is always r + distribution abbreviation.
  8. Set a random seed for reproducibility. Before generating numbers, type set.seed(123) (any integer works). Then run your random generation. Every time you run the same seed followed by the same command, you get identical results. This is crucial for sharing code or debugging.
  9. Combine multiple random steps in one script. For example, to simulate 100 coin flips (heads=1, tails=0): set.seed(42); flips <- sample(c(0,1), size = 100, replace = TRUE). Then view the result with flips.
  10. Store results in a variable for later use. Assign with my_numbers <- runif(50). Then you can compute summary statistics like mean(my_numbers) or sd(my_numbers).

Common Mistakes

  • Forgetting to set a seed when you need reproducible results. Without it, every run gives different numbers, making it hard to compare or debug.
  • Using sample() without replace = TRUE when you want repeats. For example, sample(1:3, size = 5) errors because you can't draw 5 items from a pool of 3 without replacement.
  • Confusing runif() with rnorm(). runif() gives uniform values (all equally likely within a range); rnorm() gives bell-shaped values clustered around the mean.
  • Assuming sample() works on a single number. sample(10, 1) actually samples from 1 to 10 (because R interprets a single number as a sequence). To sample from just the number 10, use sample(10, 1, replace = TRUE) or sample(c(10), 1).
  • Not checking the help for distribution parameters. For instance, rbinom() requires size and prob, not just mean and sd. Use ?rbinom to see the arguments.

Tips

  • Set a seed at the top of your script so that anyone running the whole script gets the same random sequence. Use a different seed for different analyses to avoid identical results.
  • Use set.seed() with a meaningful number (like the current year) to remember which seed you used.
  • For large simulations, avoid loops when possible—R's vectorized functions like runif(10000) are much faster than looping 10,000 times.
  • Check the length of your output with length() to ensure you generated the right number of values.
  • Use hist() or summary() to verify the distribution looks as expected. For example, hist(rnorm(1000)) should show a bell curve.
  • Remember that random numbers are pseudo-random—they come from a deterministic algorithm, so they are not truly random, but they are statistically indistinguishable from random for most purposes.

Troubleshooting

  • Error: “cannot take a sample larger than the population when 'replace = FALSE'” — This means you asked for more items than exist in your vector. Either increase the vector size, set replace = TRUE, or reduce the size argument.
  • Error: “unused argument” — You likely used a parameter that doesn't exist for that function. For example, runif(5, mean = 0) is wrong; uniform uses min and max. Check the help with ?runif.
  • Results are not reproducible even after setting a seed — This can happen if you call set.seed() inside a loop or after other random operations. Place it immediately before the random generation you want to reproduce.
  • Getting the same sequence every time even without a seed — R may reset the seed automatically when you restart the session, but if you run the same command twice in the same session, you get different numbers. If you see identical numbers, check if you accidentally assigned a constant (e.g., runif(1) was stored and you are printing the stored value).
  • Numbers look too uniform or too clustered — That's expected based on the distribution. If you need integers, use sample() or round() on continuous values, but be aware that rounding changes the distribution.

Frequently Asked Questions

  • How do I generate a random integer between 1 and 100? Use sample(1:100, size = 1) for a single integer, or sample(1:100, size = 10, replace = TRUE) for ten integers with repeats allowed.
  • What does set.seed() do exactly? It initializes the random number generator to a known state. After calling set.seed(123), any subsequent random functions produce the same sequence every time you run them, as long as you use the same seed and same order of calls.
  • Can I generate random numbers from a custom distribution? Yes, for many common distributions R has built-in functions (e.g., rgamma(), rbeta()). For a completely custom distribution, you can use the inverse transform method with runif() and the quantile function, or use rejection sampling.
  • Why do I get different numbers each time I run my script? Because you haven't set a seed. Without a seed, R uses the current time and process ID to start the generator, so results vary between runs.
  • Is there a way to generate a random matrix? Yes, use the matrix() function with random values: matrix(runif(12), nrow = 3, ncol = 4) creates a 3x4 matrix of uniform numbers. You can also use replicate() for more complex structures.
  • How do I generate random numbers that sum to a specific total? One method: generate uniform numbers, then divide by their sum and multiply by the target total. For example, to get three numbers that sum to 100: x <- runif(3); x <- x / sum(x) * 100. Note that this does not produce independent uniform values; it creates a Dirichlet-like distribution.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.