R match arrays by noncomformable margin

68 views Asked by At

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?

1

There are 1 answers

4
Nick Kennedy On

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]))
))