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

sample() function in R selects random samples from a given population. The population can be all elements of a vector, observations of a data frame, etc. For example, in the following code example, 10 elements are randomly selected a population of 100 integers, with replacement possible.

#randomly select 10 data from 100 integers, with repetition possible
sp <- sample(1:100, 10, replace=TRUE)
print(sp)
#output 
[1] 79 88 52 33 13 52 56 27 68 13

The basic form of sample() is sample(object, n, replace). When n is less than the length of object, replace option should be TRUE. Nest example shows 10 elements selected from a population of 5.

#10 data randomly selected from a given population of size 5
sp<- sample(1:5,10,replace=TRUE)
sp
#output
[1] 3 1 2 1 2 2 2 3 1 1

sample() is most useful when selecting observations from a data frame. The following example shows how to select 10 random car samples from mtcars data frame.

#using data frame mtcars in R
data(mtcars)
#randomly select 10 dintinct car samples from mtcars
car_sp <- mtcars[sample(1:nrow(mtcars), 10, replace = FALSE),]
car_sp
#output 
                  mpg cyl  disp  hp drat    wt  qsec vs am gear
Merc 230         22.8   4 140.8  95 3.92 3.150 22.90  1  0    4
Toyota Corolla   33.9   4  71.1  65 4.22 1.835 19.90  1  1    4
Merc 450SE       16.4   8 275.8 180 3.07 4.070 17.40  0  0    3
Camaro Z28       13.3   8 350.0 245 3.73 3.840 15.41  0  0    3
Merc 240D        24.4   4 146.7  62 3.69 3.190 20.00  1  0    4
Duster 360       14.3   8 360.0 245 3.21 3.570 15.84  0  0    3
Fiat X1-9        27.3   4  79.0  66 4.08 1.935 18.90  1  1    4
Dodge Challenger 15.5   8 318.0 150 2.76 3.520 16.87  0  0    3
Lotus Europa     30.4   4  95.1 113 3.77 1.513 16.90  1  1    5
Porsche 914-2    26.0   4 120.3  91 4.43 2.140 16.70  0  1    5
                 carb
Merc 230            2
Toyota Corolla      1
Merc 450SE          3
Camaro Z28          4
Merc 240D           2
Duster 360          4
Fiat X1-9           1
Dodge Challenger    2
Lotus Europa        2
Porsche 914-2       2

For getting more knowledge of R, you can watch R tutorial videos on our YouTube channel !


0 Comments

Leave a Reply

Avatar placeholder