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))
dim(out2) <- (...)and then usingapermto permute the dimensions might work, but I haven't figured out the proper incantation