R random code example

Example 1: random integer in r

random_x <- sample(1:10, 1)

# or

random_10x = sample(-1:1, size = 10, replace = T)

Example 2: generate numbers in distribution r

> runif(1)    # generates 1 random number
[1] 0.3984754
> runif(3)    # generates 3 random number
[1] 0.8090284 0.1797232 0.6803607
> runif(3, min=5, max=10)    # define the range between 5 and 10
[1] 7.099781 8.355461 5.173133

Example 3: generate numbers in distribution r

> rnorm(1)    # generates 1 random number
[1] 1.072712
> rnorm(3)    # generates 3 random number
[1] -1.1383656  0.2016713 -0.4602043
> rnorm(3, mean=10, sd=2)    # provide our own mean and standard deviation
[1]  9.856933  9.024286 10.822507

Tags:

R Example