How to randomly assign participants to groups in R?



To randomly assign participants to groups, we can use sample function.

For example, if we have a data frame called df that contains a column say Employee_ID and we want to create five groups that are stored in a vector say Grp then random assignment of participants to values in Grp can be done by using the command given below −

df$Grp<-print(sample(Grp,20,replace=TRUE))

Example 1

Consider the below data frame and vector group −

Student_ID<-sample(214215:954721,20)
df1<-data.frame(Student_ID)
df1

Output

The following dataframe is created −

  Student_ID
1  763795
2  879621
3  778568
4  261380
5  797790
6  507481
7  800390
8  390149
9  438842
10 425594
11 828031
12 780819
13 657212
14 288759
15 678103
16 476391
17 418810
18 823006
19 637735
20 814120

Add the following code to the above snippet −

Group<-1:4

In order to randomly assign student ID’s to groups in Group vector, add the following code to the above snippet −

df1$Group<-print(sample(Group,20,replace=TRUE))
[1] 4 4 2 1 3 1 4 2 4 3 2 3 4 4 4 1 4 3 1 4
df1

Output

If you execute all the above given snippets as a single program, it generates the following Output −

 Student_ID Group
1  763795   4
2  879621   4
3  778568   2
4  261380   1
5  797790   3
6  507481   1
7  800390   4
8  390149   2
9  438842   4
10 425594   3
11 828031   2
12 780819   3
13 657212   4
14 288759   4
15 678103   4
16 476391   1
17 418810   4
18 823006   3
19 637735   1
20 814120   4

Example 2

Consider the below data frame and vector group −

Employee_ID<-sample(10001:99999,20)
df2<-data.frame(Employee_ID)
df2

Output

The following dataframe is created −

 Employee_ID
1  89915
2  93083
3  99440
4  16555
5  80010
6  95122
7  49810
8  31117
9  96031
10 82851
11 45405
12 41392
13 30216
14 49501
15 42112
16 78632
17 62772
18 84564
19 52695
20 12141

Add the following code to the above snippet −

Category<-c(1,2,3,4)

In order to randomly assign employee ID’s to groups in Category vector, add the following code to the above snippet −

df2$Category<-print(sample(Category,20,replace=TRUE))
[1] 1 3 4 1 1 1 3 4 4 2 3 1 2 4 2 3 2 1 1 1
df2

Output

If you execute all the above given snippets as a single program, it generates the following Output −

 Employee_ID Category
1  89915      1
2  93083      3
3  99440      4
4  16555      1
5  80010      1
6  95122      1
7  49810      3
8  31117      4
9  96031      4
10 82851      2
11 45405      3
12 41392      1
13 30216      2
14 49501      4
15 42112      2
16 78632      3
17 62772      2
18 84564      1
19 52695      1
20 12141      1

Advertisements