4.2 Random number

To generate random integers, we use the function sample().

We first generate 8 random integers between 2 and 10 without replacement:

sample(2:10,8, replace=F) 
## [1] 10  5  6  4  7  2  3  8

The next one generate 7 integers between 2 and 10 with replacement:

sample(2:10,7, replace=T) 
## [1] 8 6 6 4 2 6 3

In general, the sample() function can also be applied to extract random element from a vector.

namelist<-c("Mary", "Peter", "John", "Susan")
sample(namelist,2)  # sample from this list
## [1] "Peter" "John"

To generate random decimal numbers, we use runif to get random uniform distribution. The following generates 2 random decimal numbers between 4.6 and 7.8:

runif(2, 4.6, 7.8) 
## [1] 7.739726 5.416660

To generate normal distribution, we use rnorm(). The following generate 4 random number that follows the normal distribution with mean being 0 and standard deviation being 1.

x <- rnorm(4, mean=0, sd=1) # standard nromal
x
## [1] -0.2169702 -0.8094769 -1.1244788  0.3853158