# [R] avoiding loops, gaining generality

Matthew Wiener mcw at ln.nimh.nih.gov
Wed Sep 29 05:58:08 CEST 1999

```Hi, all.

Given an array, I'd like to add elements whose location vectors are
permutations of one another.  For example, in a 3-dimensional array, I'd
add the elements in positions (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2)
and (3,2,1); those in positions (1,2,4), (1,4,2), (2,1,4), (2,4,1),
(4,1,2), and (4,2,1); and so on.  Elements with repeated positions
-- (1,1,2) or (1,4,4), for example -- can be ignored.

In two dimensions, what I want can be done with (x + t(x))[lower.tri(x)].

My idea for duplicating this in more than two dimensions involve loops
and if statements, and require me to write a separate function for each
number of dimensions.  Something like:

for(i1 in 1:dim(x)[1]){
for(i2 in 1:dim(x)[2]){
...
for(in in 1:dim(x)[n]){
temp.vec <- c(i1, i2, ..., in)
ans[sort(temp.vec)] <- ans[sort(temp.vec)] + x[temp.vec]
}
...
}
}

This seems like a very clunky approach, but so far I haven't come up with
anything better.

I'm wondering whether any of the R aficionados out there can recommend a
way that works for any dimension, and is reasonably efficient. In fact,
even a reasonably efficient way to do it for a fixed number of dimensions
(with a separate function for each number of dimensions) would be helpful.

I'll summarize to the list.

Thanks,

Matt

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```