# [R] [External] Re: Speeding up a loop

Tue Jul 24 20:35:28 CEST 2012

```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.

Em 23-07-2012 18:18, Reith, William [USA] escreveu:
> It looks like both ways produce the same result.
>
> -----Original Message-----
> Sent: Monday, July 23, 2012 1:05 PM
> To: Reith, William [USA]
> Subject: Re: [External] Re: [R] Speeding up a loop
>
> Hello,
>
> But that's the negation of '<', so try to negate '<=', meaning, remove the equal signs. Sorry if I wasn't very clear.
>
>
> Em 23-07-2012 17:44, Reith, William [USA] escreveu:
>> This is what I have for the yes for loop
>>
>> for(i in seq_len(nrow(x))){
>>       yes <- x[i, 1] >= a1 | x[i, 2] >= a2 | x[i, 3] <= a3 | x[i, 4]>= a4
>>       if(all(yes)) keep(i, e)
>>     }
>>
>> -----Original Message-----
>> Sent: Monday, July 23, 2012 12:14 PM
>> To: Reith, William [USA]
>> Cc: r-help
>> Subject: [External] Re: [R] Speeding up a loop
>>
>> Hello,
>>
>> I think this is a boundary issue. In your op you've said "less" not "less than or equal to".
>> Try using "<=" and ">=" to see what happens, I bet it solves it.
>>
>>
>> Em 23-07-2012 14:43, wwreith escreveu:
>>> 1.15           60	0.553555415         0.574892872
>>> 1.15	   60	0.563183983         0.564029359
>>>
>>> Shouldn't the function row out the second one, since it it higher in
>>> position 3 and lower in position 4 i.e. it should not all be yes?
>>>
>>>
>>>
>>>
>>>
>>> --
>>> View this message in context:
>>> http://r.789695.n4.nabble.com/Speeding-up-a-loop-tp4637201p4637438.ht
>>> m l Sent from the R help mailing list archive at Nabble.com.
>>>
>>> ______________________________________________
>>> R-help at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-help