Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The R %in% operator

Tags:

r

In R, I have am running the following script:

> 1:6 %in% 0:36 [1] TRUE TRUE TRUE TRUE TRUE TRUE 

Which is clearly producing a logical vector. I have read the documentation but can't seem to find an operator that would return a scalar based on the result, such that 1:6 %in% 0:36 would simply return TRUE while having 0:37 %in% 0:36 return FALSE.

Does one exist?

like image 931
dplanet Avatar asked Apr 30 '12 15:04

dplanet


People also ask

What is the OR operator in R?

OR Operator “|” The OR operator (|) works similarly, but the difference is that only at least one of the logical values should be equal to TRUE for the entire OR operation to evaluate to TRUE . This means that TRUE | TRUE equals TRUE , but also, TRUE | FALSE and FALSE | TRUE evaluates to TRUE .

What does %% in R mean?

The result of the %% operator is the REMAINDER of a division, Eg. 75%%4 = 3. I noticed if the dividend is lower than the divisor, then R returns the same dividend value.

What does the in do in R?

The %in% operator in R can be used to identify if an element (e.g., a number) belongs to a vector or dataframe. For example, it can be used the see if the number 1 is in the sequence of numbers 1 to 10.

What %>% means in R?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression.


1 Answers

You can use all

> all(1:6 %in% 0:36) [1] TRUE > all(1:60 %in% 0:36) [1] FALSE 

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36) [1] TRUE > any(1:60 %in% 0:36) [1] TRUE > any(50:60 %in% 0:36) [1] FALSE 
like image 93
nico Avatar answered Sep 24 '22 19:09

nico