为r中的索引对子集数组 [英] Subset an array for the pairs of indices in r

查看:91
本文介绍了为r中的索引对子集数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我已经进行了搜索,但是找不到我的问题的简单答案。
假设我有一个数组:

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

这不是我想要的。我希望我的输出是每对索引的一个值。实际上,我希望提取的矩阵的尺寸为2x2(而不是2x2x2)。
让您知道我尝试了循环。但是问题是我有很多数组,这将非常耗时。

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],] 
}

感谢您的帮助。

推荐答案

提供了我对您的正确理解,我们可以使用 Map

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

或简化为矩阵使用 mapply

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

地图是<$的包装c $ c> mapply 不会简化结果,从而生成列表(而不是矩阵)。

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

这篇关于为r中的索引对子集数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆