[R] Condition %in%

David Winsemius dwinsemius at comcast.net
Mon Sep 13 23:54:46 CEST 2010


On Sep 13, 2010, at 5:43 PM, Mestat wrote:

>
> Hi listers,
> If I would like to check if a variable contains certain value, I would
> write:
> if (10 %in% x)
> And If I would like to check the opposite, that 10 is not into x.  
> How would
> be?

Not sure about your terminology, "into x"?.  why wouldn't it be

if (x %in% 10)
  ... oh, I see, it's that single argument to if() thing again.
 > x <- 10
 > y <- c(10,9)

 > if (y %in% x) TRUE
[1] TRUE
Warning message:
In if (y %in% x) TRUE :
   the condition has length > 1 and only the first element will be used

?all
?any

 > if (all(y %in% x)) TRUE else FALSE
[1] FALSE
 > if (all(x %in% y)) TRUE else FALSE
[1] TRUE

 > if (any(x %in% y)) TRUE else FALSE
[1] TRUE
 > if (any(x %in% y)) TRUE else FALSE
[1] TRUE

So decide what you really want to test. If you want to check to see if  
two groups are the same from a set theoretic viewpoint then setdiff()  
could be used.


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list