Skip to content

all combinations with replacement not ordered

5 messages · Konstantin Tretiakov, William Dunlap, (Ted Harding) +1 more

#
Is this what you want?
   f <- function (x, m)  combn(x + m - 1, m) - seq_len(m) + 1

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
On 07-Nov-2013 13:38:29 Konstantin Tretiakov wrote:
1 1 1
  1 1 2
  1 1 3
  1 2 2
  1 2 3
  1 3 3
  2 2 2
  2 2 3
  2 3 3
  3 3 3

The following will do that:

u <- c(1,2,3)
unique(t(unique(apply(expand.grid(u,u,u),1,sort),margin=1)))

#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    1    1    2
# [3,]    1    1    3
# [4,]    1    2    2
# [5,]    1    2    3
# [6,]    1    3    3
# [7,]    2    2    2
# [9,]    2    3    3
#[10,]    3    3    3

There may be a simpler way!
Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 07-Nov-2013  Time: 17:04:50
This message was sent by XFMail
#
Well, you can create the expand.grid data frame programmatically via:

u <- 1:3
len <- length(u)
v <-do.call(expand.grid, split(rep(u,len),rep(seq_len(len),e=len)))

And then you can use unique.array to get the unique rows after the sort:

unique(t(apply(v,1,sort)))

However, I agree with your sentiments. Not only does this seem
inelegant, but it will not scale well.

I would imagine a recursive approach would be more efficient -- as
then only the sets you need would be produced and there'd be no
sorting, etc. -- but I have neither the time nor interest to work it
out.

... and I bet someone already has done this in some R package anyway.

Cheers,
Bert
On Thu, Nov 7, 2013 at 9:04 AM, Ted Harding <Ted.Harding at wlandres.net> wrote:

  
    
#
... and actually, since u can be assumed to be of the form shown,

v <-do.call(expand.grid, split(rep(u,len),rep(u,e=len)))


should do.

-- Bert
On Thu, Nov 7, 2013 at 10:06 AM, Bert Gunter <bgunter at gene.com> wrote: