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'?
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.
%% gives Remainder. %/% gives Quotient. So 6 %% 4 = 2. In your example b %% a , it will vectorised over the values in “a”
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.
%>% 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.
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.)
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With