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?
This will give you the minimum difference for each:
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: