0

I have a problem where I have k items, say {0,1}, and I have to enumerate all possible N draws, say N=3. That is, I am trying to find all possible samples of a given size from a vector, with replacement.

I can get there via the following loop approach:

for (i1 in c(0,1)){
    for (i2 in  c(0,1)){
        for (i3 in c(0,1)){
             print(paste(i1,i2i3,collapse="_")) 
}}} 

However, this feels like a kludge. Is there a better way to do this using base R?

AeroX
  • 3,387
  • 2
  • 25
  • 39
learner
  • 1,895
  • 2
  • 19
  • 21
  • Nice question, +1! I didn't find anything useful by searching for "all possible samples with replacement", so I edited your question to make it easier to find for future users with the same problem. – Stephan Kolassa Dec 17 '14 at 14:56

2 Answers2

5

You can use interaction:

items <- c(0, 1)
n <- 3

levels(interaction(rep(list(items), n), sep = "_"))
# [1] "0_0_0" "1_0_0" "0_1_0" "1_1_0" "0_0_1" "1_0_1" "0_1_1" "1_1_1"
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
4

If vec is your vector and n is the number of times you draw from vec, to enumerate all the possibilities, try:

  expand.grid(replicate(n,vec,simplify=FALSE),
       KEEP.OUT.ATTRS=FALSE,stringsAsFactors=FALSE)

For instance:

 vec<-0:1
 n<-3
 expand.grid(replicate(n,vec,simplify=FALSE),
       KEEP.OUT.ATTRS=FALSE,stringsAsFactors=FALSE)
 #   Var1 Var2 Var3
 #1    0    0    0
 #2    1    0    0
 #3    0    1    0
 #4    1    1    0
 #5    0    0    1
 #6    1    0    1
 #7    0    1    1
 #8    1    1    1  

The number of permutations rises very quickly; try the above only for small vectors and small n.

nicola
  • 24,005
  • 3
  • 35
  • 56