matlab - Indexing a vector by an array in R -


in matlab , numpy, can index vector array of indices , result of same shape out, e.g.

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 np = 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 vector array of indices returns vector:

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 idiomatic way in r perform vectorized lookup preserves array shape?

you can't specify dimensions through subsetting alone in r (afaik). here workaround:

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

produces:

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

dim<-(...) allows use dimension setting function dim<- result rather side effect case.

you can stuff like:

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

but slow.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -