R: How to extract sets of multidimensional array values according to another matrix

前端 未结 2 452
终归单人心
终归单人心 2021-01-26 09:11

Suppose I have a 4 dimensional n x n x n x n array A. A is a distance matrix, such that A[i,j,l,k] is the distance from location i,j to location pair l,k. Suppose I have an nxn

相关标签:
2条回答
  • 2021-01-26 09:53

    My guess is that there is a more elegant way of doing this. Its inspired by DWin's solution but takes care of all potential combinations of getting from a type 0 to a type 1 cell. Let me know if you guys think of a better way

    > type
         [,1] [,2] [,3]
    [1,]    0    0    1
    [2,]    0    1    0
    
    
    
    type.0 = which(type == 0, arr.ind=T) #locations of type 0 cells
    type.1 = which(type == 1, arr.ind=T) #locations of type 1 cells
    
    nlocs0 = length(type.0[,1]) #number of locations of type 0
    nlocs1 = length(type.1[,1]) #number of locations of type 1
    
    reploc0 = rbind( do.call(rbind, rep(list(type.0), nlocs1)) ) #rbinded on top of itself nloc1 times
    reploc1 = rbind( do.call(rbind, rep(list(type.1[1,]), nlocs0)) ) #rbinding the first location of type.1 on top of itself nlocs0 times
    
    
    if(nlocs1>1){
      for(i in 2:nlocs1){
        reploc1 = rbind( rbind( do.call(rbind, rep(list(type.1[i,]), nlocs0)) ), reploc1)
      } 
    }
    
    d0_1 = A[cbind(reploc0,reploc1)]
    
    0 讨论(0)
  • 2021-01-26 10:15

    I guess you have changed the request from the one stated in the first paragraph. See if this answers the second version.

     A [ cbind( which(T == 0, arr.ind=TRUE), which(T == 1, arr.ind=TRUE) )]
    #[1] 1 1
    

    (At first I thought you might need abind but cbind works fine.)

    0 讨论(0)
提交回复
热议问题