What does %% mean in R
The infix operator %>%
is not part of base R, but is in fact defined by the package magrittr
(CRAN) and is heavily used by dplyr
(CRAN).
It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.
What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris
gets passed to head()
:
library(magrittr)
iris %>% head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
Thus, iris %>% head()
is equivalent to head(iris)
.
Often, %>%
is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris
is passed to head()
, then the result of that is passed to summary()
.
iris %>% head() %>% summary()
Thus iris %>% head() %>% summary()
is equivalent to summary(head(iris))
. Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.
What does %% function mean in R?
%...% operators
%>%
has no builtin meaning but the user (or a package) is free to define operators of the form %whatever%
in any way they like. For example, this function will return a string consisting of its left argument followed by a comma and space and then it's right argument.
"%,%" <- function(x, y) paste0(x, ", ", y)
# test run
"Hello" %,% "World"
## [1] "Hello, World"
The base of R provides %*%
(matrix mulitiplication), %/%
(integer division), %in%
(is lhs a component of the rhs?), %o%
(outer product) and %x%
(kronecker product). It is not clear whether %%
falls in this category or not but it represents modulo.
expm The R package, expm, defines a matrix power operator %^%
. For an example see Matrix power in R .
operators The operators R package has defined a large number of such operators such as %!in%
(for not %in%
). See http://cran.r-project.org/web/packages/operators/operators.pdf
igraph This package defines %--% , %->% and %<-% to select edges.
lubridate This package defines %m+% and %m-% to add and subtract months and %--% to define an interval. igraph also defines %--% .
Pipes
magrittr In the case of %>%
the magrittr R package has defined it as discussed in the magrittr vignette. See http://cran.r-project.org/web/packages/magrittr/vignettes/magrittr.html
magittr has also defined a number of other such operators too. See the Additional Pipe Operators section of the prior link which discusses %T>%
, %<>%
and %$%
and http://cran.r-project.org/web/packages/magrittr/magrittr.pdf for even more details.
dplyr The dplyr R package used to define a %.%
operator which is similar; however, it has been deprecated and dplyr now recommends that users use %>%
which dplyr imports from magrittr and makes available to the dplyr user. As David Arenburg has mentioned in the comments this SO question discusses the differences between it and magrittr's %>%
: Differences between %.% (dplyr) and %>% (magrittr)
pipeR The R package, pipeR, defines a %>>%
operator that is similar to magrittr's %>% and can be used as an alternative to it. See http://renkun.me/pipeR-tutorial/
The pipeR package also has defined a number of other such operators too. See: http://cran.r-project.org/web/packages/pipeR/pipeR.pdf
postlogic The postlogic package defined %if%
and %unless%
operators.
wrapr The R package, wrapr, defines a dot pipe %.>%
that is an explicit version of %>%
in that it does not do implicit insertion of arguments but only substitutes explicit uses of dot on the right hand side. This can be considered as another alternative to %>%
. See https://winvector.github.io/wrapr/articles/dot_pipe.html
Bizarro pipe. This is not really a pipe but rather some clever base syntax to work in a way similar to pipes without actually using pipes. It is discussed in http://www.win-vector.com/blog/2017/01/using-the-bizarro-pipe-to-debug-magrittr-pipelines-in-r/ The idea is that instead of writing:
1:8 %>% sum %>% sqrt
## [1] 6
one writes the following. In this case we explicitly use dot rather than eliding the dot argument and end each component of the pipeline with an assignment to the variable whose name is dot (.
) . We follow that with a semicolon.
1:8 ->.; sum(.) ->.; sqrt(.)
## [1] 6
Update Added info on expm package and simplified example at top. Added postlogic package.
Update 2 The development version of R has defined a |>
pipe. Unlike magrittr's %>%
it can only substitute into the first argument of the right hand side. Although limited, it works via syntax transformation so it has no performance impact.
Meaning of Symbol %% in R
%>%
means whatever you want it to mean, in Base R anyway:
> %>%
Error: unexpected SPECIAL in "%>%"
(which means that symbol is not defined.)
Binary operators are ones that have an input from the left and from the right of the operator, just like *
, +
etc. You use them as you would mathematically like a * b
, which R turns into the call '*'(a, b)
. R allows you to add your own binary operators via the %foo%
syntax, with foo
replace by whatever you want, as long as it hasn't already been used by R, which includes %*%
and %/%
for example.
`%foo%` <- function(x, y) paste("foo", x, "and foo", y)
> 1 %foo% 2
[1] "foo 1 and foo 2"
%>%
takes on a specific and well-defined meaning once you load the magrittr R package for example, where it is used as a pipe operator might be in a Unix shell to chain together a series of function calls.
What does %*% mean in R
Use ?'%*%'
to get the documentation.
%*%
is matrix multiplication. For matrix multiplication, you need an m x n
matrix times an n x p
matrix.
What does the %% operator mean in R?
The help, ?magrittr::`%<>%`
, answers all your questions, if you are refering to magrittr`s compound assignment pipe-operator:
[...]
%<>%
is used to update a value
by first piping it into one or more rhs expressions, and then
assigning the result. For example,some_object %<>% foo %>% bar
is
equivalent tosome_object <- some_object %>% foo %>% bar
. It must be
the first pipe-operator in a chain, but otherwise it works like%>%
.
So
library(magrittr)
set.seed(1);x <- rnorm(5)
x %<>% abs %>% sort
x
# [1] 0.1836433 0.3295078 0.6264538 0.8356286 1.5952808
is the same as
set.seed(1);x <- rnorm(5)
x <- sort(abs(x))
x
# [1] 0.1836433 0.3295078 0.6264538 0.8356286 1.5952808
What does the double percentage sign (%%) mean?
The "Arithmetic operators" help page (which you can get to via ?"%%"
) says
‘
%%
’ indicates ‘x mod y’
which is only helpful if you've done enough programming to know that this is referring to the modulo operation, i.e. integer-divide x
by y
and return the remainder. This is useful in many, many, many applications. For example (from @GavinSimpson in comments), %%
is useful if you are running a loop and want to print some kind of progress indicator to the screen every nth iteration (e.g. use if (i %% 10 == 0) { #do something}
to do something every 10th iteration).
Since %%
also works for floating-point numbers in R, I've just dug up an example where if (any(wts %% 1 != 0))
is used to test where any of the wts
values are non-integer.
What does !! operator mean in R
The !!
and {{
operators are placeholders to flag a variable as having been quoted. They are usually only needed if you intend to program with the tidyverse
.
The tidyverse
likes to leverage NSE (non-standard Evaluation) in order to reduce the amount of repetition. The most frequent application is towards the "data.frame"
class, in which expressions/symbols are evaluated in the context of a data.frame before searching other scopes.
In order for this to work, some special functions (like in the package dplyr
) have arguments that are quoted. To quote an expression, is to save the symbols that make up the expression and prevent the evaluation (in the context of tidyverse
they use "quosures", which is like a quoted expression except it contains a reference to the environment the expression was made).
While NSE is great for interactive use, it is notably harder to program with.
Lets consider the dplyr::select
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
iris <- as_tibble(iris)
my_select <- function(.data, col) {
select(.data, col)
}
select(iris, Species)
#> # A tibble: 150 × 1
#> Species
#> <fct>
#> 1 setosa
#> 2 setosa
#> 3 setosa
#> 4 setosa
#> 5 setosa
#> 6 setosa
#> 7 setosa
#> 8 setosa
#> 9 setosa
#> 10 setosa
#> # … with 140 more rows
my_select(iris, Species)
#> Error: object 'Species' not found
we encounter an error because within the scope of my_select
the col
argument is evaluated with standard evaluation and
cannot find a variable named Species
.
If we attempt to create a variable in the global environemnt, we see that the funciton
works - but it isn't behaving to the heuristics of the tidyverse
. In fact,
they produce a note to inform you that this is ambiguous use.
Species <- "Sepal.Width"
my_select(iris, Species)
#> Note: Using an external vector in selections is ambiguous.
#> ℹ Use `all_of(col)` instead of `col` to silence this message.
#> ℹ See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
#> This message is displayed once per session.
#> # A tibble: 150 × 1
#> Sepal.Width
#> <dbl>
#> 1 3.5
#> 2 3
#> 3 3.2
#> 4 3.1
#> 5 3.6
#> 6 3.9
#> 7 3.4
#> 8 3.4
#> 9 2.9
#> 10 3.1
#> # … with 140 more rows
To remedy this, we need
to prevent evaluation with enquo()
and unquote with !!
or just use {{
.
my_select2 <- function(.data, col) {
col_quo <- enquo(col)
select(.data, !!col_quo) #attempting to find whatever symbols were passed to `col` arugment
}
#' `{{` enables the user to skip using the `enquo()` step.
my_select3 <- function(.data, col) {
select(.data, {{col}})
}
my_select2(iris, Species)
#> # A tibble: 150 × 1
#> Species
#> <fct>
#> 1 setosa
#> 2 setosa
#> 3 setosa
#> 4 setosa
#> 5 setosa
#> 6 setosa
#> 7 setosa
#> 8 setosa
#> 9 setosa
#> 10 setosa
#> # … with 140 more rows
my_select3(iris, Species)
#> # A tibble: 150 × 1
#> Species
#> <fct>
#> 1 setosa
#> 2 setosa
#> 3 setosa
#> 4 setosa
#> 5 setosa
#> 6 setosa
#> 7 setosa
#> 8 setosa
#> 9 setosa
#> 10 setosa
#> # … with 140 more rows
In summary, you really only need !!
and {{
if you are trying to apply NSE programatically
or do some type of programming on the language.
!!!
is used to splice a list/vector of some sort into arguments of some quoting expression.
library(rlang)
quo_let <- quo(paste(!!!LETTERS))
quo_let
#> <quosure>
#> expr: ^paste("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
#> "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y",
#> "Z")
#> env: global
eval_tidy(quo_let)
#> [1] "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
Created on 2021-08-30 by the reprex package (v2.0.1)
What do the %op% operators in mean? For example %in%?
Put quotes around it to find the help page. Either of these work
> help("%in%")
> ?"%in%"
Once you get to the help page, you'll see that
‘%in%’ is currently defined as
‘"%in%" <- function(x, table) match(x, table, nomatch = 0) > 0’
Since time
is a generic, I don't know what time(X2)
returns without knowing what X2
is. But, %in%
tells you which items from the left hand side are also in the right hand side.
> c(1:5) %in% c(3:8)
[1] FALSE FALSE TRUE TRUE TRUE
See also, intersect
> intersect(c(1:5), c(3:8))
[1] 3 4 5
Related Topics
Long/Bigint/Decimal Equivalent Datatype in R
What Is the Purpose of Setting a Key in Data.Table
Read Multiple CSV Files into Separate Data Frames
Using Data.Table Package Inside My Own Package
Select Groups With More Than One Distinct Value
Starting Shiny App After Password Input
How to Format a Number as Percentage in R
Pasting Two Vectors With Combinations of All Vectors' Elements
Calculate Cumulative Sum (Cumsum) by Group
Getting Warning: " 'Newdata' Had 1 Row But Variables Found Have 32 Rows" on Predict.Lm
Assign Multiple Columns Using := in Data.Table, by Group
Capitalize the First Letter of Both Words in a Two Word String
What Are the "Standard Unambiguous Date" Formats For String-To-Date Conversion in R
How to Assign a Unique Id Number to Each Group of Identical Values in a Column
Using Regex in R to Find Strings as Whole Words (But Not Strings as Part of Words)