Thomas
Thomas

Reputation: 1454

Randomly assign treatment within differently sized groups + dplyr

I have individuals within four groups.

df <- data.frame(group=c(rep(1, 90),
                     rep(2, 110),
                     rep(3, 105),
                     rep(4, 95)),
             id=1:400)

I'd like to randomly assign each individual within each group to one of five treatments. I can do that for each group seperately, but I was wondering how that would be done in a dplyr routine?

In the end, the df should look sth like this:

id   group   treat
 1   1       5
 2   1       4
 3   1       4
 4   1       3
 5   1       3

Upvotes: 1

Views: 952

Answers (2)

akrun
akrun

Reputation: 887901

We can use data.table

library(data.table)
setDT(df)[, treat := sample(5, .N, replace = TRUE)][]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389275

We can use sample with replace = TRUE

library(dplyr)
df %>% mutate(treat = sample(5, n(), replace = TRUE))

#    group  id treat
#1       1   1     3
#2       1   2     4
#3       1   3     5
#4       1   4     4
#5       1   5     5
#6       1   6     1
#7       1   7     5
#....

Obviously, you can do it directly as well without any packages

df$treat <- sample(5, nrow(df), replace = TRUE)

Also a thing to note here is sample(5) works same as sample(1:5) as it is a single digit number it is automatically expanded to 1:5 within sample.

Upvotes: 2

Related Questions