Re: [R] all combinations with replacement

From: Jorge Ivan Velez <jorgeivanvelez_at_gmail.com>
Date: Thu, 21 Apr 2011 16:11:52 -0400

Hi Kehl,

How large are n and k in your case? Using Dimitris' approach and I got the following timings for 1000 replicates:

# function based on Dimitri's reply
foo <- function(n, k){
  r <- expand.grid(rep(list(0:n), k))

       subset(r, rowSums(r) == n)
      }

# a second try
foo2 <- function(n, k){
  r <- expand.grid(rep(list(0:n), k))

     r[rowSums(r) == n, ]
      }

# n = 6, k = 3
> system.time(replicate(1000, foo(6, 3)))

   user system elapsed
  1.336 0.015 1.345

> system.time(replicate(1000, foo2(6, 3)))

   user system elapsed
  1.210 0.008 1.209

HTH,
Jorge

> R.version

               _
platform       x86_64-apple-darwin9.8.0
arch           x86_64
os             darwin9.8.0
system         x86_64, darwin9.8.0
status         Patched
major          2
minor          13.0
year           2011
month          04
day            18
svn rev        55504
language       R

version.string R version 2.13.0 Patched (2011-04-18 r55504)

On Thu, Apr 21, 2011 at 3:52 PM, Kehl Dániel <> wrote:

> Thank you.
> I only need those where the rowsum = n.
> I could choose those with code, but I dont think it is efficient that way.
>

> daniel
>
> 2011-04-21 12:33 keltezéssel, Dimitris Rizopoulos írta:
>
>
>> expand.grid(rep(list(0:6), 3))
>>
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

        [[alternative HTML version deleted]]



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 21 Apr 2011 - 20:14:29 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 21 Apr 2011 - 20:40:33 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive