简体   繁体   中英

compatea value in two vectors and assign the compared results into a new vector in R

I have a vector to be append, and here is the code,which is pretty slow due to the nrow is big.

All I want to is to speed up. I have tried c() and append() and both seems not fast enough. And I checkd Efficiently adding or removing elements to a vector or list in R?

Here is the code:

compare<-vector()

for (i in 1:nrow(domin)){

  for (j in 1:nrow(domin)){
      a=0
    if ((domin[i,]$GPA>domin[j,]$GPA) & (domin[i,]$SAT>domin[j,]$SAT)){
      a=1  
    }
    compare<-c(compare,a)
  }
  print(i)
}

I found it is hard to figure out the index for the compare if I use

   #compare<-rep(0,times=nrow(opt_predict)*nrow(opt_predict))

The information you want would be better placed in a matrix:

v1 <- 1:3
v2 <- c(1,2,2)
mat1 <- outer(v1,v1,`>`)
mat2 <- outer(v2,v2,`>`)
both <- mat1 & mat2

To see which positions the inequality holds for, use which :

which(both,arr.ind=TRUE)
#      row col
# [1,]   2   1
# [2,]   3   1

Comments:

  • This answer should be a lot faster than your loop. However, you are really just sorting two vectors, so there is probably a faster way to do this than taking the exhaustive set of inequalities...
  • In your case, there is only a partial ordering (since, for a given i and j , it is possible that neither one is strictly greater than the other in both dimensions). If you were satisfied with sorting first on v1 and then on v2 , you could use the data.table package to easily get a full ordering:

     set.seed(1) v1 <- sample.int(10,replace=TRUE) v2 <- sample.int(10,replace=TRUE) require(data.table) DT <- data.table(v1,v2) setkey(DT) DT[,rank:=.GRP,by='v1,v2'] 

    which gives

      v1 v2 rank 1: 1 8 1 2: 3 3 2 3: 3 8 3 4: 4 2 4 5: 6 7 5 6: 7 4 6 7: 7 10 7 8: 9 5 8 9: 10 4 9 10: 10 8 10 

    It depends on what you were planning to do next.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM