Skip to content

[External] Re: Speeding up a loop

1 message · Rui Barradas

#
Hello,

Anyway, I've redid part of the function in order to accomodate 1. larger 
increments and 2. keep if equal or not. So, here's the complete version 
and forget my two previous mails.

to.keep <- function(x, increment = 1e4, keep.if.equal = FALSE){
     keep <- function(i, env){
         env$ires <- env$ires + 1
         if(env$ires > env$curr.rows){
             env$result <- rbind(env$result, matrix(nrow=increment, 
ncol=nc))
             env$curr.rows <- env$curr.rows + increment
         }
         env$result[env$ires, ] <- x[i, ]
     }

     x  <- as.matrix(x)
     a1 <- x[, 1]
     a2 <- x[, 2]
     a3 <- x[, 3]
     a4 <- x[, 4]
     nc <- ncol(x)

     e <- new.env()
     e$curr.rows <- increment
     e$result <- matrix(nrow=e$curr.rows, ncol=nc)
     e$ires <- 0
     if(keep.if.equal){
         for(i in seq_len(nrow(x))){
             yes <- a1[i] >= a1 | a2[i] >= a2 | a3[i] <= a3 | a4[i] >= a4
             if(all(yes[-i])) keep(i, e)
         }
     }else{
         for(i in seq_len(nrow(x))){
             no <- a1[i] <= a1 & a2[i] <= a2 & a3[i] >= a3 & a4[i] <= a4
             if(!any(no[-i])) keep(i, e)
         }
     }
     e$result[seq_len(e$ires), 1:nc]
}


I hope this finally settles it.

Rui Barradas

Em 23-07-2012 18:18, Reith, William [USA] escreveu: