R runif – Picking Values From A Uniform Distribution

This article about R’s runif function is part of a series we’re doing about generating random numbers using the R language. We previously profiled how to use  the sample function to randomly select items from a list of values. R Sample is useful for selecting a sample from a finite set of items.

Uniform Distribution in R

But what if the observations in our sample can be decimals? For example, if we make widgets and measure them, most errors will be small. We are not likely to have 2 three inch widgets and 3 four inch widgets in our sample. A more likely sampling might be: 2.9, 3.1, 3.2, 3.0, 2.85.

If we believe values of a distribution are evenly allocated, we refer to this as a uniform distribution. Ever value of the distribution has an equal chance of being selected. This is a common topic in first year statistics classes.

runif – Values From a Uniform distribution

To generate values from a uniform distribution, R provides the runif in R function. It can accept three parameters:

  • Number of observations desired
  • Starting point for distribution
  • Ending point for distribution

The example below requests 5 observations selected from a uniform distribution ranging between 4 and 6.

# runif in r
runif(5,4,6)

[1] 4.974123 4.478758 5.742496 5.484664 5.193645

More about the Uniform Distribution

As mentioned above, the uniform distribution is the starting point for advanced probability studies.  It defines a range between two points. Any point in that range has equal likelihood of being selected. This mimics many real world processes.

Random Number Generator

The runif in R function is useful when simulating probability problems. It works for random number generation as well – you can use it to generate lists of random numbers (random data). You can also embed it in a for loop to control a more complex decision model.

As we repeatedly sample from a uniform distribution, that average of our sample will begin to assume the shape of a normal distribution (aka a bell curve). This is a good lead in to our next sampling function, the R’s rnorm function.

R’s runif function is part of R’s collection of built in probability distributions. Other distributions include the binomial distribution, the standard distribution (standard normal), the exponential distribution, the beta distribution, and the Poisson distribution. This random function covers uniform random numbers.

Distribution Function Validation

As an aside, R also has a number of built in functions you can use to validate the results. Since these operate as a pseudo random number generator, you can analyze the random variable set created and test them against expected patterns. Look at a histogram, mean, quantile function results, and the standard deviation.

To read other articles in the series, select one of the following links:

Scroll to top
Privacy Policy