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

David Winsemius dwinsemius at comcast.net
Sat Oct 29 17:10:54 CEST 2011


On Oct 29, 2011, at 9:08 AM, Suleyman K 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.

You did say "combinations" rather than permutations, so:

 > colSums(combn(0:5, 3))
  [1]  3  4  5  6  5  6  7  7  8  9  6  7  8  8  9 10  9 10 11 12

If you instead meant "permutations", then consider this:

 > rowSums(expand.grid(0:5,0:5, 0:5))
   [1]  0  1  2  3  4  5  1  2  3  4  5  6  2  3  4  5  6  7  3  4  5   
6  7  8  4  5  6  7  8  9  5  6  7
  [34]  8  9 10  1  2  3  4  5  6  2  3  4  5  6  7  3  4  5  6  7  8   
4  5  6  7  8  9  5  6  7  8  9 10
  [67]  6  7  8  9 10 11  2  3  4  5  6  7  3  4  5  6  7  8  4  5  6   
7  8  9  5  6  7  8  9 10  6  7  8
[100]  9 10 11  7  8  9 10 11 12  3  4  5  6  7  8  4  5  6  7  8  9   
5  6  7  8  9 10  6  7  8  9 10 11
[133]  7  8  9 10 11 12  8  9 10 11 12 13  4  5  6  7  8  9  5  6  7   
8  9 10  6  7  8  9 10 11  7  8  9
[166] 10 11 12  8  9 10 11 12 13  9 10 11 12 13 14  5  6  7  8  9 10   
6  7  8  9 10 11  7  8  9 10 11 12
[199]  8  9 10 11 12 13  9 10 11 12 13 14 10 11 12 13 14 15

 > table(rowSums(expand.grid(0:5,0:5, 0:5)))

  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
  1  3  6 10 15 21 25 27 27 25 21 15 10  6  3  1

A056150 Number of combinations for each possible sum when throwing 3  
(normal) dice.
http://oeis.org/A056150


>
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list