Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The percent sign in R

Tags:

r

I recently read some source code for a R package called 'pathifier'. In the source code, it uses the percent sign.

if (0 %in% xs) {
si <- NULL
cat(file = logfile, append = TRUE, "skipping pathway ", 
i, " (0 in xs)\n")
}

What does %in% mean in this function? Does it just mean the regular 'in'?

like image 211
yuanhangliu1 Avatar asked Dec 12 '13 20:12

yuanhangliu1


People also ask

What is a percent sign in R?

The %.% operator in dplyr allows one to put functions together without lots of nested parentheses. The flanking percent signs are R's way of denoting infix operators; you might have used %in% which corresponds to the match function or %*% which is matrix multiplication.

What does %% mean in R?

%% gives Remainder. %/% gives Quotient. So 6 %% 4 = 2. In your example b %% a , it will vectorised over the values in “a”

How do I type a percent sign?

On a US Keyboard layout, the percent sign is located on the numeral 5 key above the R and T. To insert % hold down the Shift key and press the 5 key. If you have a different Keyboard layout, it may be in some other place, but you can also insert it by holding down the Alt key and typing 037 on the numeric keypad.

What does >%> mean 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.


2 Answers

The in reserved word can only be used in for loops. The %in% function is different. As noted in the documentation at ?"%in%", is defined as:

"%in%" <- function(x, table) match(x, table, nomatch = 0) > 0

So, it is essentially match. In English, x %in% y returns a vector of logical of the same length as x, with TRUE every time the corresponding element of x exists at least once in y.

The reason why there are % around it is to mark it as a "infix" operator. (I don't know if that is the exact term.)

like image 166
nograpes Avatar answered Oct 22 '22 06:10

nograpes


The useR is given the capacity to create new infix functions and the dispatch mechanism will recognize functions whose names begin and end with %. Say you wanted to make an infix operator that replicated a value n number of times:

 `%rep%` <- function(x,y) rep(x,y)
  10 %rep% 5
  # [1] 10 10 10 10 10

Another example of doing such will be found on the help page for ?match which discusses %in% as well as demonstrates how to make an %w/o% infix operator. The section in the R Language Reference that describes this is 10.3.4: "Special operators".

like image 20
IRTFM Avatar answered Oct 22 '22 08:10

IRTFM