简体   繁体   English

通过R中的数组索引向量

[英]Indexing a vector by an array in R

In MATLAB and numpy, you can index a vector by an array of indices and get a result of the same shape out, eg 在MATLAB和numpy中,您可以按索引数组对向量进行索引,并得到形状相同的结果,例如

A = [1 1 2 3 5 8 13];
B = [1 2; 2 6; 7 1; 4 4];
A(B)

## ans =
##  
##     1    1
##     1    8
##    13    1
##     3    3

or 要么

import numpy as np
a = np.array([1, 1, 2, 3, 5, 8, 13])
b = np.reshape(np.array([0, 1, 1, 5, 6, 0, 3, 3]), (4, 2))
a[b]

## array([[ 1,  1],
##        [ 1,  8],
##        [13,  1],
##        [ 3,  3]])

However, in R, indexing a vector by an array of indices returns a vector: 但是,在R中,通过索引数组对向量进行索引会返回向量:

a <- c(1, 1, 2, 3, 5, 8, 13)
b <- matrix(c(1, 2, 7, 4, 2, 6, 1, 4), nrow = 4)
a[b]

## [1]  1  1 13  3  1  8  1  3

Is there an idiomatic way in R to perform vectorized lookup that preserves array shape? R中是否有惯用的方法来执行保留数组形状的矢量化查找?

这不是很优雅,但可以

matrix(a[b],nrow=nrow(b))

You can't specify dimensions through subsetting alone in R (AFAIK). 您不能仅通过R(AFAIK)中的子集来指定尺寸。 Here is a workaround: 这是一种解决方法:

`dim<-`(a[b], dim(b))

Produces: 生产:

     [,1] [,2]
[1,]    1    1
[2,]    1    8
[3,]   13    1
[4,]    3    3

dim<-(...) just allows us to use the dimension setting function dim<- for its result rather than side effect as is normally the case. dim<-(...)仅允许我们将尺寸设置功能dim<-用于其结果,而不是通常的副作用。

You can also do stuff like: 您还可以执行以下操作:

t(apply(b, 1, function(idx) a[idx]))

but that will be slow. 但这会很慢。

Option 1: if we do not need to keep the original values in b, we could simply 选项1:如果我们不需要将原始值保留在b中,则可以简单地

"Caveat: the values in b will be over-written"
b[] = a[b]
b
#      [,1] [,2]
# [1,]    1    1
# [2,]    1    8
# [3,]   13    1
# [4,]    3    3

Option 2: if want to retain the values in b, An easy workaround could be 选项2:如果要保留b中的值,可以采用一种简单的解决方法

c = b  # copy b to c
c[] = a[c]
c
#      [,1] [,2]
# [1,]    1    1
# [2,]    1    8
# [3,]   13    1
# [4,]    3    3

Actually I found Option 2 is easy to follow and clean. 实际上,我发现选项2易于遵循和清洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM