Skip to content

How to apply a function to a multidimensional array, based on its indices

1 message · Rui Barradas

#
Hello,

Your way is much better than to mess with the dim attribute, like I did. 
But,

"If you can create a data.frame or matrix that has the indices"
Actually, it must be a matrix, indices can't be of type list.


A way to avoid loops/apply altogether, and much faster, is the one 
creating K3
(K is the result from the op.)

n <- 20

t2 <- system.time({
K2 <- array(0,dim=c(n,n,n,n))
mtx <- data.matrix( expand.grid(x1=1:n,x2=1:n,y1=1:n,y2=1:n) )
K2[mtx] <- apply(mtx, 1, function(x) x["x1"]*x["y2"] - 
sin(x['x2']*x['y1']) )
})

t3 <- system.time({
K3 <- array(0,dim=c(n,n,n,n))
mtx <- data.matrix( expand.grid(x1=1:n,x2=1:n,y1=1:n,y2=1:n) )
K3[mtx] <- with(data.frame(mtx), x1*y2 - sin(x2*y1))
})


It's also woth noting that both use much more memory than the loop 
version because the index matrix can be large.

Rui Barradas
Em 15-05-2012 11:00, r-help-request at r-project.org escreveu: