[R] While loop working with TRUE/FALSE?

David Winsemius dwinsemius at comcast.net
Thu Feb 2 14:14:50 CET 2012

On Feb 2, 2012, at 6:55 AM, Chris82 wrote:

> 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))

This suggests a lack of understanding re: how to use logical  
functions. The any() function is completely superfluous here. It will  
return exactly the same vector as would:

q1[i] == w1) &  (q2[i] == w2)

If you wanted to use any() to pick out cases where either q1[i] == w1  
or q2[i]==w2 then do not put an ampersand between those arguments but  
rather a comma.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT

More information about the R-help mailing list