Dear all, I want to compare a huge vector with selected element from a matrix. 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? -- Kind regards, Ran [[alternative HTML version deleted]]
William Dunlap
2013-May-10 16:57 UTC
[R] compare vector with selected element from a matrix
Try using a 2-column matrix, with columns formed from C and D, to subscript A. E.g., > A <- matrix(101:132, nrow=8, ncol=4) > C <- seq_len(nrow(A))^2 %% nrow(A) + 1 > D <- seq_len(nrow(A))^3 %% ncol(A) + 1 > for(j in seq_len(nrow(A))) print(A[C[j], D[j]]) [1] 110 [1] 105 [1] 126 [1] 101 [1] 110 [1] 105 [1] 126 [1] 101 > A[cbind(C, D)] [1] 110 105 126 101 110 105 126 101 Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com> -----Original Message----- > From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf > Of Ran Gu > Sent: Friday, May 10, 2013 12:39 AM > To: r-help at r-project.org > Subject: [R] compare vector with selected element from a matrix > > Dear all, > > I want to compare a huge vector with selected element from a matrix. > > 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? > > > -- > Kind regards, > Ran > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.