user56474
user56474

Reputation: 115

Select same elements matrix in R

I would like select 5 elements, no 25, as fast as possible. It takes a long time run on large vectors:

a = c(1,2,5,2,3)
b = c(2,4,1,4,5)
d = matrix(1:25,nrow=5,ncol=5)

result = array(NA,dim=length(a))

for (i in 1:length(a)) { result[i] = d[a[i],b[i]] }

OR (more slow)

result<-sapply(1:length(a), function(x)  d[a[x],b[x]] )

Upvotes: 1

Views: 118

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193627

Just use matrix indexing:

d[cbind(a, b)]
# [1]  6 17  5 17 23

For more details, see ?Extract, where you will find the following lines:

A third form of indexing is via a numeric matrix with the one column for each dimension: each row of the index matrix then selects a single element of the array, and the result is a vector.

There are also a few examples in the "Examples" section at the same help page.

Upvotes: 2

Related Questions