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) 
## [1]  6  8  4 10  5  9  3  2

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

sample(2:10,7, replace=T) 
## [1]  9 10 10 10  9  4  5

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] 6.707066 6.467373

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.3503315 -0.3547852 -0.5211190  0.2816110