Was it helpful?

Question

How to simulate discrete uniform random variable in R?

R ProgrammingServer Side ProgrammingProgramming

There is no function in base R to simulate discrete uniform random variable like we have for other random variables such as Normal, Poisson, Exponential etc. but we can simulate it using rdunif function of purrr package.

The rdunif function has the following syntax −

> rdunif(n, b , a)

Here,

n = Number of random values to return

b = Maximum value of the distribution, it needs to be an integer because the distribution is discrete

a = Minimum value of the distribution, it needs to be an integer because the distribution is discrete

Example

Let’s say you want to simulate 10 ages between 21 to 50. We can do this as follows −

> library(purrr)
> rdunif(10,b=50,a=21)
[1] 38 33 28 36 48 32 47 27 29 24

Now suppose we want to simulate 10 ages and the maximum age is 100 then it can be done as shown below −

> rdunif(10,100)
[1] 2 80 50 50 82 68 45 72 81 25

We can also simulate discrete uniform distribution for negative integers as shown in the below example −

> rdunif(10,10,-5)
[1] 3 -1 -3 3 6 5 3 5 -5 9

We can also create a table of discrete uniform random variable. Let’s say we want to generate 20 random values between -3 and +3 then it can be done as shown below −

> table(rdunif(20, 3, -3))

-3 -2 -1 0 1 3
2 4 4 3 3 4

https://www.tutorialspoint.com/what-is-the-use-of-tilde-operator-in-r

raja
Published on 06-Jul-2020 18:17:59
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top