How can I perform cluster sampling in R (With Examples)?

Cluster sampling in R can be performed using the ‘cluster.sample’ function from the ‘survey’ package. This function takes a data frame as an argument and returns a vector of indices which can be used to select the clusters. To illustrate, if we have a data frame ‘df’ and we want to select 2 clusters at random, we can use the following command: indices <- cluster.sample(df, 2). This will return a vector of indices, which can be used to select the two clusters from the data frame.


Researchers often take samples from a population and use the data from the sample to draw conclusions about the population as a whole.

One commonly used sampling method is cluster sampling, in which a population is split into clusters and all members of some clusters are chosen to be included in the sample.

This tutorial explains how to perform cluster sampling in R.

Example: Cluster Sampling in R

Suppose a company that gives city tours wants to survey its customers. Out of ten tours they give one day, they randomly select four tours and ask every customer to rate their experience on a scale of 1 to 10.

The following code shows how to create a fake data frame in R to work with:

#make this example reproducible
set.seed(1)

#create data frame
df <- data.frame(tour = rep(1:10, each=20),
                 experience = rnorm(200, mean=7, sd=1))

#view first six rows of data frame
head(df)

  tour experience
1    1   6.373546
2    1   7.183643
3    1   6.164371
4    1   8.595281
5    1   7.329508
6    1   6.179532

And the following code shows how obtain a sample of customers by randomly selecting four tours and including every member in those tours in the sample:

#randomly choose 4 tour groups out of the 10
clusters <- sample(unique(df$tour), size=4, replace=F)

#define sample as all members who belong to one of the 4 tour groups
cluster_sample <- df[df$tour %in% clusters, ]

#view how many customers came from each tour
table(cluster_sample$tour)

 2  7  8 10 
20 20 20 20 

From the output we can see that:

  • 20 customers from tour group #2 were included in the sample.
  • 20 customers from tour group #7 were included in the sample.
  • 20 customers from tour group #8 were included in the sample.
  • 20 customers from tour group #10 were included in the sample.

Thus, this sample is composed of 80 total customers that came from 4 different tour groups.

Related: How to Use %in% Operator in R

Understanding Different Types of Sampling Methods
Stratified Sampling in R
Systematic Sampling in R

x