Skip to content
Prev 294500 / 398502 Next

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

Hello,

Try

K <- array(0,dim=c(2,2,2,2)) #dimensions will be much larger
for(x1 in 1:2){
  for(y1 in 1:2)  {
    for(x2 in 1:2)    {
      for(y2 in 1:2)      {
        K[x1,y1,x2,y2] <-  x1*y2 - sin(x2*y1) #this is just a dummy
function.
      }  
    }
  }
}


fun <- function(x){
	x1 <- x[1]  # these are
	x2 <- x[2]  # not
	y1 <- x[3]  # really
	y2 <- x[4]  # needed
	x1*y2 - sin(x2*y1) # could have used x[1], etc
}


res <- apply(expand.grid(1:2, 1:2, 1:2, 1:2), 1, fun)
dim(res) <- c(2, 2, 2, 2)
res

all.equal(K, res)
[1] TRUE

See the help pages
?expand.grid
?apply


Hope this helps,

Rui Barradas

math_daddy wrote
--
View this message in context: http://r.789695.n4.nabble.com/How-to-apply-a-function-to-a-multidimensional-array-based-on-its-indices-tp4629940p4629955.html
Sent from the R help mailing list archive at Nabble.com.