如何在 r 的列表中找到最大值的 i j k 索引?

How do I find the i j k indices of the maximum value in a list in r?

我在 R 中有一个列表,其中有数据 (Data):

#create data
tmintest=array(1:100, c(12,256,512))

#create the list
Variable <- list(varName = c("tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin","tmin"),level = c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA))
Data     <- tmintest
xyCoords <- list(x = seq(-40.37,64.37,length.out=420), y = seq(25.37,72.37,length.out=189))
Dates <- list(start = seq(as.Date("2012-01-01"), as.Date("2015-12-31"), by="days"), end=seq(as.Date("2012-01-01"), as.Date("2015-12-31"), by="days"))
All <- list(Variable = Variable,Data=Data, xyCoords=xyCoords,Dates=Dates)

如何准确找到 ALL$Data 中出现最大数字的位置?比如如果是第4行第100列第一个'slice'或者'grid'我要回:[1,4,100].

我试过 which.max(All$Data) 但只有 returns 一个数字?

which支持arr.ind,即returns条件的数组索引。不幸的是,which.max 没有这样的参数,所以我们可以将这些值与最大值进行比较。

head( which(All$Data == max(All$Data), arr.ind = TRUE) )
#      dim1 dim2 dim3
# [1,]    4    9    1
# [2,]    8   17    1
# [3,]   12   25    1
# [4,]    4   34    1
# [5,]    8   42    1
# [6,]   12   50    1

我在这里要谨慎一点:当精度涉及大量小数位时,浮点数的严格相等性测试可能会成为问题。请参阅 Why are these numbers not equal?, Is floating point math broken?, and https://en.wikipedia.org/wiki/IEEE_754 对此进行很好的讨论。

更好的测试是严格不等式之一,寻找容差。在这里我将使用 1e-5 因为我们知道它明显小于数字范围(1 到 100),但如果您的实数更精确,您可能需要更适合您需要的东西。

head( which( (max(All$Data) - All$Data) < 1e-5, arr.ind = TRUE) )
#      dim1 dim2 dim3
# [1,]    4    9    1
# [2,]    8   17    1
# [3,]   12   25    1
# [4,]    4   34    1
# [5,]    8   42    1
# [6,]   12   50    1

请注意,如果您将公差值 1e-5 设置得太低 ,您可能会开始丢失值。这里不会发生(因为你的数据要大得多)。