4

Although I have searched for, I could not find a straightforward answer to my question. Suppose I have an array:

    vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
result <- array(c(vector1,vector2),dim = c(3,3,2))

Now, I want to subset this array in such a way as to get elements from certain rows and columns. For example:

result[1,3,1:2]
result[3,1,1:2]

since I have many indices, they are sotred in

rowind=c(1,3)
colind=c(3,1)

For subsetting, I have tried to use vectors of rows and columns in this way

dim(result[rowind,colind,1:2])

[1] 2 2 2

This is not what I want. I want my output to be one value for each pair of the indices. In fact, I want my extracted matrix to have a dimension of 2x2 (not 2x2x2). To let you know I have tried "loop".But the problem is that I have many numbers of arrays and it would be very time-consuming.

result_c=matrix(NA,nrow=2,ncol=2)

for (i in 1:2){
  result_c[i,]=result[rowind[i],colind[i],] 
}

Thanks for your help.

3 Answers3

1

Provided I understood you correctly, we can use Map

Map(function(i, j) result[i, j, 1:2], rowind, colind)
#[[1]]
#[1] 13 13
#
#[[2]]
#[1] 3 3

Or simplified as a matrix using mapply

mapply(function(i, j) result[i, j, 1:2], rowind, colind)
#     [,1] [,2]
#[1,]   13    3
#[2,]   13    3

Map is a wrapper to mapply which does not simplify the results, thereby producing a list (rather than a matrix).

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
1

We could pass a matrix of indexes to subset the data

result[cbind(rep(rowind, each = 2), rep(colind, each = 2), 1:2)]
#[1] 13 13  3  3
akrun
  • 874,273
  • 37
  • 540
  • 662
1

R matrices fill in column-major order, meaning that elements in the same column correspond to consecutive elements in the data. You can use this fact to compute the vector index of a matrix element from its row and column indices.

I don't understand the need for 3 dimensions in the question, so I'm giving an example with 2:

m <- array(seq_len(4),dim=c(3,2))
ixc <- c(1,2,1)
ixr <- c(1,1,2)
# > m  
#      [,1] [,2]
# [1,]    1    4
# [2,]    2    1
# [3,]    3    2
m[(ixc-1)*nrow(m)+ixr]
# [1] 1 4 2
Metamorphic
  • 732
  • 6
  • 16