Subset an array for the pairs of indices in r

放肆的年华 提交于 2020-01-05 07:20:12

问题


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.


回答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).




回答2:


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


来源:https://stackoverflow.com/questions/51192521/subset-an-array-for-the-pairs-of-indices-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!