[R] OT: algorithm for generating all possible combinations withreplacement

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Nov 25 09:36:00 CET 2005


"Ales Ziberna" <aleszib at gmail.com> writes:

> Does this do what you want?
> n<-10
> k<-5
> expand.grid(rep(list(1:n),k))
> 
> However be carful, even this small example prouces matrix with100000 rows.

I'm not sure this is what was wanted, since it is generating the same
samples multiple times. Consider

m <- expand.grid(rep(list(1:3),3))

table(apply(apply(m,1,sort),2,paste,collapse=" "))

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
    1     3     3     3     6     3     1     3     3     1

It is possible that "Globe Trotter" wanted essentially the names of
the table, or maybe unique(t(apply(m,1,sort))). There's probably a
faster way of generating those. However, to use them for anything
probabilistic, you also need to keep track of the counts (using
multinomial coefficients).
 

> Best,
> Ales Ziberna
> ----- Original Message ----- 
> From: "Globe Trotter" <itsme_410 at yahoo.com>
> To: <fedora-list at redhat.com>; <r-help at stat.math.ethz.ch>
> Sent: Friday, November 25, 2005 6:22 AM
> Subject: [R] OT: algorithm for generating all possible combinations 
> withreplacement
> 
> 
> > Dear all,
> >
> > I have n objects and I want to select k of these with replacement. Do you 
> > know
> > of code which would generate all the possible arrangements? Note that this 
> > is
> > different from the selection of k of n objects without replacement and 
> > wanting
> > to generate all the possible permutations.
> >
> > Any suggestions? Existing C code would be fantastic btw, but I would be 
> > happy
> > with an algorithm.
> >
> > Best wishes!
> >
> > ______________________________________________
> > R-help at stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide! 
> > http://www.R-project.org/posting-guide.html
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> 

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list