1

Suppose I have:

aa <- seq(2,10, length=3)
bb <- seq(20,30, length=2)
cc <- seq(10,11, length=2)

fun <- function(a,b,c) {return(a+b-c)}

out <- array(dim=c(length(aa), length(bb), length(cc)))
for(i in 1:length(aa)) {
  for(j in 1:length(bb)) {
    for(k in 1:length(cc)) {
      out[i,j,k] <- fun(aa[i], bb[j], cc[k])
    }
  }
}

Aiming for a faster alternative, I then tried apply() as follows

b2 <- rep(bb, each=2)
abc <- rbind(rep(aa, each=2*2), rep(bb, each=2), rep(cc,6))
out2 <- apply(abc, 2, function(x){ fun(x[1], x[2], x[3]) } )

This basically does the same calculation as before but I couldn't get the format of "out2" to be in the array as "out". Can you correct the below code so that out and out2 are exactly the same? Thanks so much in advance

out2 <- array(out2, dim=dim(out))
1
  • 1
    I think making it into an array via dim(out2) <- (...) and then using aperm to permute the dimensions might work, but I haven't figured out the proper incantation Commented May 9, 2014 at 2:23

2 Answers 2

2

Though not hugely flexible, you could rearrange the entire problem like:

outer(outer(aa,bb,"+"),cc,"-")

identical(out,outer(outer(aa,bb,"+"),cc,"-"))
#[1] TRUE
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @thelatemail But I was using that fun() as a simplest example and have something else much more complicated.. Nice trick btw, perhaps there is something similar about parallelizing that chunk of code using some shorts of of parrallel apply that you can share?
2

Not sure if there's a way to do it in one step, but here it is in two more steps:

#your original code
b2 <- rep(bb, each=2)
abc <- rbind(rep(aa, each=2*2), rep(bb, each=2), rep(cc,6))
out2 <- apply(abc, 2, function(x){ fun(x[1], x[2], x[3])})

out2 = matrix(out2,ncol=4,nrow=3,byrow=T)
out2 = array(c(out2[,c(1,3)],out2[,c(2,4)]),dim=dim(out))
identical(out,out2)
#[1] TRUE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.