R Programming

Creating a random sequence using sample() in R

We provide effective and economically affordable training courses for R and Python, Click here for more details and course registration !

It is not uncommon to generate random sequences in R programming. sample() function provides the feasibility of generating such random objects from given vectors, either with or without replacement. The following code shows an example that 32 numbers with replacement drawn from 50 integers from 1 to 50.

#random sequence drawn with replacement from given vector
vec_replace <- sample(1 : 50, size = 32, replace = T)  

vec_replace

#output
[1]  1  3 48 20 14 37 39 42 34  9 43 14  6 18 32 28 32 32 39 44 33  9 40 2 41 43 21 50 14 32 25  3

Alternatively, random sequence can be drawn without replacement, which is shown in the following code.

#random sequence drawn without replacement from given vector
vec__no_replace <- sample(1 : 50, size = 32, replace = F)  

vec__no_replace
#output
[1] 48 10 16 33  3  9  1 49 34 32 36 37 29  7 44 24 41 11 23 39 19 20 21 27 50 42 47 15 40 17  8 14

sample() function provides also the option to specify the expected probability associated with each seed element, such that the generated sequence complies with this specified ratio. The next example code shows 1000 random numbers drawn from 5 integers from 3 to 7, with the probability specified for each number.

#random sequence drawn with specified probabilities
vec_prob <- sample(3:7, size = 1000, replace = T,
       prob = c(0.1, 0.2, 0.15, 0.25, 0.3))

vec_prob
#output
  [1] 3 3 4 6 4 7 5 6 5 7 3 7 6 7 5 6 7 6 6 6 3 6 6 5 6 6 5 7 4 5 5 5 6 5 7 6 7 4 3 4 6 5 7 
,,, 
[953] 4 4 7 7 5 5 6 7 6 4 6 6 5 4 5 7 4 6 6 6 7 5 3 6 6 7 7 5 6 6 7 6 6 4
 [987] 6 7 6 7 7 7 7 5 5 7 5 7 6 6

table(vec_prob)/1000*100

  #output , the frequency is close to the specified #probabilities
 3    4    5    6    7 
 9.5 20.5 15.2 26.0 28.8 

You can also watch full video of R tutorial on our YouTube channel.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago