# 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 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)

 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.

The runif function is useful when simulating probability problems. You can use it to generate lists of random numbers.  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.

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