Usage of make.unique for sample IDs

Viewed 63

I'm trying to come up with a quick way of assigning some treatment IDs and...honestly I could do this faster on paper now but I have crossed the line to where I can't stop until I figure this out.

I want to make a table with 35 rows - each row would contain a vector with 9 numbers (between 1 and 12) but EACH ROW MUST BE UNIQUE.

I tried the quick solution that popped into my head:

data.frame(replicate(9,sample(1:12,35, rep = TRUE)))

but this obviously doesn't work for me because of "rep=TRUE" and "rep=FALSE" can't work as written because of the sample pool (1:12). Is there a way of adding make.unique to get at this?

Thanks!

2 Answers

There are probably more clever ways to go about this, but one relatively fail safe approach is to generate way more rows than you need and then simply take the top X unique() rows. Building off your code:

set.seed(1)
x <- data.frame(replicate(9,sample(1:12,1e6, rep = TRUE)))
#how many rows did we make?
nrow(x)
#> [1] 1000000
#how many unique rows?
nrow(unique(x))
#> [1] 999906
#show the top two rows while showing how to get 35 rows total
head(unique(x)[1:35, ],2)
#>   X1 X2 X3 X4 X5 X6 X7 X8 X9
#> 1  9  6  8  3 12  7 11  5  5
#> 2  4  1  8 11 12 11 11  7  6

Created on 2019-10-07 by the reprex package (v0.3.0)

Assuming you want a unique combination, you can use combn to generate all possible combos and then take a sample of 35 random rows:

# all combos
x <- as.data.frame(t(combn(1:12, 9)))
# 35 random rows
x[sample(1:choose(12,9), 35), ]
Related