# [R] While loop working with TRUE/FALSE?

Petr PIKAL petr.pikal at precheza.cz
Thu Feb 2 15:20:02 CET 2012

```Hi

>
> Thanks to Berend and the others,
>
> I've found a solution which works fine for my problem.
>
> I have not only 2 vectors, but also 4.
> Question is, if q1 and q2 is equal to w1 and w2.
> The computational time is very short, also for large data.
>
> q1 <- c(9,5,1,5)
> q2 <- c(9,2,1,5)
>
> w1 <- c(9,4,4,4,5)
> w1 <- c(9,4,4,4,5)
>
> v <- vector()
> for (i in 1:(length(q1))){
> v[i] <- any((q1[i] == w1) &  (q2[i] == w2))
> }

If i understand correctly you want to know if any value in q1 is also in
w1 and q2 is in w2.
Therefore
any((q2[2] == w2) & (q1[2] == w1))
is true in only if there is common elements in both vector pairs which is
what

> (q1 %in% w1) & (q2 %in% w2)
[1]  TRUE FALSE FALSE  TRUE

does.

For small vectors (several values) timing will be probably similar,
however with moderate vectors with few thousand values there is
considerable speedup.

> q1<-sample(q1, 10000, replace=T)
> q2<-sample(q2, 10000, replace=T)
> w1<-sample(w1, 100000, replace=T)
> w2<-sample(w2, 100000, replace=T)
> v2<- vector()
> system.time({
+ for (i in 1:(length(q1))){
+ v2[i] <- any((q1[i] == w1) &  (q2[i] == w2))
+ }})
user  system elapsed
34.36    1.69   36.16
>
> system.time(v<-((q1 %in% w1) & (q2 %in% w2)))
user  system elapsed
0.01    0.00    0.02
> all.equal(v,v2)
[1] TRUE

Regards
Petr

>
>
> best regards
>
> --
> View this message in context: http://r.789695.n4.nabble.com/While-loop-
> working-with-TRUE-FALSE-tp4348340p4351214.html
> 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