Reputation: 115
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
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