[R] R help with different combinations of vectors of different sizes

William Dunlap wdunlap at tibco.com
Sat Oct 29 16:56:09 CEST 2011


Another approach is to use expand.grid to create a
data.frame of all possible combinations of elements
of its input vectors:
   rowSums(expand.grid(0:5, 0:5, 0:5))

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of R. Michael
> Weylandt
> Sent: Saturday, October 29, 2011 7:46 AM
> To: Suleyman K
> Cc: r-help at r-project.org
> Subject: Re: [R] R help with different combinations of vectors of different sizes
> 
> Just add another outer wrapper:
> 
> outer(1:5, outer(1:5, 1:5, "+"), "+")
> 
> If you are going to arbitrarily long tuples, it may be worthwhile to
> put this in a wrapper like so:
> 
> tupleSums <- function(vec, n){
>      stopifnot(all.equal(n, as.integer(n)))
>      n <- as.integer(n)
>      if (n == 1L) return(vec)
>      ans <- outer(vec, vec, "+")
>      if (n == 2L) return(ans)
>      else{
>           for (i in 3:n) ans <- outer(vec, ans, "+")
>       }
>       return(ans)
> }
> 
> Though this really could be made  much more efficient if you want:
> e.g., for the n = 4 case, it would be better to take outer( outer(vec,
> vec, "+"), outer(vec, vec, "+"), "+").
> 
> Michael
> 
> On Sat, Oct 29, 2011 at 9:08 AM, Suleyman K <s.karmv at gmail.com> wrote:
> > Hi,
> >
> > I am trying to get different combinations of a vector of different size and
> > find their sum. For example, if I have a vector (i,j) where i and j can be
> > anything from 0 to 5, i get these combinations (0,0), (0,1), (1,0), (1,1),
> > (2,0), ...... (5,5) and find sum of these as 0, 1, 1, 2, ..... , 10. I used
> > outer functions to get this and it worked. What if I have a vector (i,j,k)
> > where all i, j , and k can be anything from 0 to 5. I want to do the same
> > thing here. Get all the combinations and sum them up. (0,0,0) (0,0,1),
> > (0,1,0), (1,0,0), .... (5,5,5) How can I get these combinations and find
> > their sums? Thank you very much in advance.
> >
> > Uka
> >
> >        [[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.
> >
> 
> ______________________________________________
> 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.



More information about the R-help mailing list