I want to compare a huge vector with selected element from a matrix in R.
A is a matrix and B is a vector. I want to compare each element of B with selected element from A. C and D are selection criteria. They are vectors of same length as B. C specifies the row number of A, and D specifies the column number. A is of dimension 10*100, and B,C,D are all vectors of length 72000. Code with for loop:
for ( j in 1:length(B) ){
E[j] <- B[j] >= A[ C[j], D[j] ]
}
This is too slow. I vectorize this by define a vector including elements from A first:
A1 <- array(0, length(B))
A2 <- A[,D]
for ( j in 1:length(B) ){
A1[j] <- A2[ C[j], j ]
}
E <- B >= A1
This is still too slow. Is there a better way to this?
A[cbind(C,D)]
you get a vector with one value for each row in A. If you subset using multiple vectors (for exampleA[C,D]
) you will receieve alength(C)
xlength(D)
array. Both are useful when appropriate but it is important to understand these are not the same! - MatthewS