0

Working with two arrays in R.

array1[x,y]
array2[x,y,t]

and I would like to compute an array3[x,y] that holds the t index that defines minimum difference between array2 and array1. These arrays were read in from netcdf files. It would be good to avoid a loop. Any help/insight is greatly appreciated.

A loop example might be similar to:

for i in 1:nx {
  for j in 1:ny {
     for k in 1:nt {
        mindiff[i,j,k] = array1[i,j]-array2[i,j,k]
     }
    #the minimum values over the k dimension
    result[i,j] = sapply(mindiff, 3, min)
  }
}

Would like result[i,j] to be the index values of k rather than the actual min values?

Matt
  • 1
  • 2
  • 1
    Please provide [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – akrun Jun 21 '15 at 05:06
  • `...like to compute an array3[x,y] that holds the t index...` sounds a little confusing to me. And you ask for array3[two params], and the continue about mindiff[3 params] and result[2 params]. Which is which? – jcoppens Jun 23 '15 at 16:32

1 Answers1

0

This will give you the minimum difference for each:

library("plyr")
library("matrixStats")
result <- t(laply(1:(dim(array1)[2]), function(j) rowMins(array1[, j, ] - array2[, j])))

If you wanted the smallest absolute difference you'd need to use abs.

For the index of each, you'd need to nest a further laply and use which.min:

library("plyr")
result <- laply(1:nrow(array2),
  function(i) laply(1:ncol(array2),
  function(j) which.min(abs(array1[i, j, ] - array2[i, j]))
))
Nick Kennedy
  • 12,510
  • 2
  • 30
  • 52
  • Thanks, Nick for the help. – Matt Jun 21 '15 at 22:11
  • @Matt did the latter of those address your problem? If the arrays are large, it's worth considering using the `.parallel` option of the outer `laply` especially if you're on a machine that supports `registerDoMC` (i.e. not Windows). – Nick Kennedy Jun 21 '15 at 22:24
  • @nick_k thanks again, I got a partial solution working. One follow up question is: with the indices in result[i,j], which represent the values of t, how can I use those back in say array1[i,j,t] and collapse the t dimension? – Matt Jun 22 '15 at 23:17
  • @Matt `fin <- matrix(array1[cbind(c(row(result)), c(col(result)), c(result))], nrow = nrow(result))` – Nick Kennedy Jun 23 '15 at 03:44