How to index a multidimensional R array dynamically?

前端 未结 3 382
我寻月下人不归
我寻月下人不归 2021-01-20 12:52

I am working on some data in R that consist of four-dimensional arrays composed of three spatial dimensions and a time dimension: x, y, z, t. For some of my analyses, I woul

相关标签:
3条回答
  • 2021-01-20 13:12

    I'm probably missing something, but don't you simply want a4d[indices[,1],indices[,2],indices[,3],]?

    0 讨论(0)
  • 2021-01-20 13:18

    I think you are looking for:

    apply(a4d, 4, `[`, indices)
    

    And to check that our results match:

    result1 <- matrix(result[,5], ncol = 10)
    result2 <- apply(a4d, 4, `[`, indices)
    identical(result1, result2)
    # [1] TRUE
    
    0 讨论(0)
  • 2021-01-20 13:19

    Accessing by each dimension individually does not work as @tilo-wiklund or I expect. Instead of 23 rows across 10 time steps, the result is a 23x23x23 cube across the 10 time steps.

    r.idvdim <- a4d[indices[,1],indices[,2],indices[,3],]
    r.apply  <- apply(a4d, 4, `[`, indices)
    r.cbind  <- matrix(a4d[lookup],ncol=nt)
    
    dim(r.idvdim)     # [1] 23 23 23 10
    dim(r.apply)      # [1] 23 10
    dim(r.cbind)      # [1] 23 10
    
    0 讨论(0)
提交回复
热议问题