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
- Open RStudio and create a new script (optional). Click File > New File > R Script (or use
Ctrl+Shift+Non Windows/Linux,Cmd+Shift+Non Mac). You can also type directly in the Console, but a script makes it easier to edit and rerun. - Generate a single random number from a uniform distribution (0 to 1). Type
runif(1)and pressCtrl+Enter(orCmd+Enteron Mac) if in a script. The output is one decimal between 0 and 1. For example, you might see[1] 0.3723. - 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. - 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. - Sample random integers (discrete uniform). Use
sample(1:10, size = 4)to pick four distinct integers from 1 to 10. To allow repeats, addreplace = TRUE:sample(1:6, size = 5, replace = TRUE)simulates rolling a die five times. - Sample from a character vector or custom set. For example,
sample(c("red", "green", "blue"), size = 2)picks two colors without replacement. Addreplace = TRUEif you want duplicates allowed. - 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, andrt(5, df = 10)for t-distribution. The pattern is alwaysr+ distribution abbreviation. - 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. - 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 withflips. - Store results in a variable for later use. Assign with
my_numbers <- runif(50). Then you can compute summary statistics likemean(my_numbers)orsd(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()withoutreplace = TRUEwhen 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()withrnorm().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, usesample(10, 1, replace = TRUE)orsample(c(10), 1). - Not checking the help for distribution parameters. For instance,
rbinom()requiressizeandprob, not justmeanandsd. Use?rbinomto 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()orsummary()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 thesizeargument. - Error: “unused argument” — You likely used a parameter that doesn't exist for that function. For example,
runif(5, mean = 0)is wrong; uniform usesminandmax. 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()orround()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, orsample(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 callingset.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 withrunif()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 usereplicate()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
- Max Data Entry Services LLP: What It Is & How It Works
- How to Turn On Track Changes in Excel
- How to Access Text Import Wizard in Excel
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets Inventory Spreadsheet: Setup and TipsYes. Google Sheets can serve as an inventory spreadsheet for a small shop, office, classroom, or household: list…
- Center Text in Excel: Keyboard Shortcut and How to Use ItTo center text horizontally in Excel for Microsoft 365 on Windows, select the cell or cells and press…
- How to Add a Watermark in a Word Document on Any PageIn Word for Microsoft 365 on Windows, open the document and choose Design > Watermark to add a…
- Debt Payoff Calculator Excel Template: Build Your PlanYes. You can build a debt payoff calculator in Excel with columns for each debt’s balance, APR, planned…
- Power Query Reference: What It Does and When to Use ItIn Excel Power Query, a reference is a new query built from the result of an existing query.…
- Budget and Balance Sheet: Key DifferencesA budget is a forward-looking plan for income and expenses over a future period, while a balance sheet…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.