## 10.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) 
##   5  2 10  9  7  4  8  3

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

sample(2:10,7, replace=T) 
##  10  8  9  5  5  5  2

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
##  "John"  "Peter"

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

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.5259096  1.5450039  1.1077966  0.3269604