【问题标题】:Subsetting multidimensional array using matrix in R使用 R 中的矩阵对多维数组进行子集化
【发布时间】:2016-03-02 10:45:21
【问题描述】:

我有一个 4 维水温数组 [经度、纬度、深度、月],我想根据行和列分别为经度和纬度的矩阵以及深度级别的值来提取月度温度。结果将是可变深度 [lon, lat, month] 的每月温度的 3 维数组。

举个例子:

set.seed(1)    
temperature <- array(rnorm(10), rep(3,4))
depth <- matrix(c(NA, sample(1:3, 8, replace = TRUE)), 3, 3)

我查看了How to index a multidimensional R array dynamically? 和R use matrix to select row of multidimensional array,但不知道该怎么做?

非常感谢任何帮助。

【问题讨论】:

  • 你如何处理NA?您要选择哪个月份?请提供预期的输出。
  • NA 是没有可用温度数据的位置(陆地),所以我不想在这些情况下做任何事情,只将它们保留为 NA,因为这样以后更容易绘制。我想选择所有月份,因此选择 3d 输出。

标签: arrays r multidimensional-array


【解决方案1】:

可能还有一段路要走,但这是一个尝试:

#get the indices relative to lon, lat and depth
threeIndices<-cbind(c(row(depth)),c(col(depth)),c(depth))
#repeat each row of the above to host a different month value
threeIndices<-threeIndices[rep(1:nrow(threeIndices),dim(temperature)[4]),]
#define the month index
fourthIndex<-rep(1:dim(temperature)[4],each=nrow(threeIndices)/dim(temperature)[4])
#putting all together
allIndices<-cbind(threeIndices,fourthIndex)
#subsetting and putting in an array
array(temperature[allIndices],dim(temperature)[c(1,2,4)])

【讨论】:

  • @ColonelBeauvel 我非常同意你的观点,如果你只是说“数组非常丑陋”,我会给你 +1 和遗憾,而不是投票给它。跨度>
  • 只需删除似乎没有执行您想要的操作的代码。
  • @RomanLuštrik 完成。我正在等待 OP 的反馈,因为我不确定哪个是正确的。现在回想起来,我更加确信第一行是错误的。
【解决方案2】:

Nicola 的回答很有帮助。我想出了一种可能更快的方法,而无需根据建议单独指定每个月。

#get the indices relative to lon, lat and depth
threeIndices <- cbind(c(row(depth)),c(col(depth)),c(depth))
# subset and put back in array
temperature.depth <- array(apply(temperature, 4, `[`, threeIndices), dim = dim(temperature)[c(1,2,4)])

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2021-04-29
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多