Skip to content
Prev 275868 / 398506 Next

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: