使用类似数组中的数据过滤3D数组

时间:2016-07-24 19:24:20

标签: arrays r optimization

我有两个三维数组,其中一个包含数据,另一个包含元数据。元数据是日期签名,因此可以使用以下内容生成示例:

datamatrix <- array(data = c(rep(0,9), rep(0,9),(sample(0:100, 9)/1000), (sample(30:50, 9)/100), (sample(70:80,9)/100), (sample(30:50,9)/100), rep(0,9), rep(0,9)), dim = c(3,3,8))
timematrix <- array(data = c(sample(1:20), sample(30:50, 9), sample(70:90, 9), sample(110:130,9), sample(150:170,9), sample(190:210,9), sample(230:250,9), sample(260:280,9)), dim = c(3,3,8))

我希望构建一个新的3D数组,其中包含第一个矩阵(datamatrix)和一堆NA的数据,以便i中的元素datamatrix 1}}落入最终timematrix 3D数组中的相应日期(从workingdata中的相应元数据中导出),如下所示:

workingdata <- array(data = NA,
                 dim = c(3,3,365))

for (i in 1:length(datamatrix)){
  location <- i
  locationguide <- location%%9
  locationfinal <- locationguide%%3
  if (locationfinal == 0){
    a <- 3
    b <- 3
  }
  if (locationfinal == 1){
    a <- 1
    b <- 1
  }  
  if (locationfinal == 2){
    a <- 1
    b <- 2
  }
  if (locationfinal == 3){
    a <- 1
    b <- 3
  }
  if (locationfinal == 4){
    a <- 2
    b <- 1
  }
  if (locationfinal == 5){
    a <- 2
    b <- 2
  }
  if (locationfinal == 6){
        a <- 2
        b <- 3
      }
  if (locationfinal == 7){
    a <- 3
    b <- 1
  }
  if (locationfinal == 8){
    a <- 3
    b <- 2
  }
  value <- datamatrix[i]
  day <- timematrix[i]
  workingdata[a,b,day] <- datamatrix[i]
}

我正在使用的数据集是数千列宽且等效的长行。当前的方法完成了这项工作,但是它需要在实际数据中永远使用for循环,并且编码它将是荒谬的,因为这需要所有if。有谁知道更好的过滤数据的方法吗?

对于我想要的观看者友好的概念,来自ESRI的图像总结如下: http://pro.arcgis.com/en/pro-app/tool-reference/space-time-pattern-mining/GUID-42A31756-6518-41E9-A900-2C892AF4023A-web.png

我正在为时间拍摄一个z维度,每天有一个块,其中观察值在z轴上落入其适当的行,但保留在x和y维度的原始位置。

2 个答案:

答案 0 :(得分:2)

我不确定你的for循环究竟是做什么的,而且它可能不会完全按你要做的去做。不确定。例如,检查((1:30)%%9)%%3

的结果

但是,根据您对问题的描述,您可能希望执行以下操作:

workingdata <- array(data = NA, dim = c(3,3,365))
for (i in 1:dim(datamatrix)[1]) {
  for (j in 1:dim(datamatrix)[1]) {
    workingdata[i, j, timematrix[i, j, ]] <- datamatrix[i, j, ]
  }
}

请注意,如果您的0中有timematrix天(例如您的示例数据中),则这不适用,因为R有1个基于索引的。

答案 1 :(得分:0)

最终答案:Axeman的解决方案采用以下方法在三个方面起作用:

workingdata <- array(data = NA, dim = c(3,3,365))

for (i in 1:dim(datamatrix)[1]) {
  for (j in 1:dim(datamatrix)[2]) {
    for(k in 1:dim(datamatrix)[3]){
      workingdata[i, j, timematrix[i, j, k]] <- datamatrix[i, j, k]
    }
  }
}