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
R: What are operators like %in% called and how can I learn about them?
There are several different things going on here with the percent symbol:
Binary Operators
As several have already pointed out, things of the form %%
, %in%
, %*%
are binary operators (respectively modulo, match, and matrix multiply), just like a +
, -
, etc. They are functions that operate on two arguments that R recognizes as being special due to their name structure (starts and ends with a %
). This allows you to use them in form:
Argument1 %fun_name% Argument2
instead of the more traditional:
fun_name(Argument1, Argument2)
Keep in mind that the following are equivalent:
10 %% 2 == `%%`(10, 2)
"hello" %in% c("hello", "world") == `%in%`("hello", c("hello", "world"))
10 + 2 == `+`(10, 2)
R just recognizes the standard operators as well as the %x%
operators as special and allows you to use them as traditional binary operators if you don't quote them. If you quote them (in the examples above with backticks), you can use them as standard two argument functions.
Custom Binary Operators
The big difference between the standard binary operators and %x%
operators is that you can define custom binary operators and R will recognize them as special and treat them as binary operators:
`%samp%` <- function(e1, e2) sample(e1, e2)
1:10 %samp% 2
# [1] 1 9
Here we defined a binary operator version of the sample function
"%" (Percent) as a token in special function
The meaning of "%"
in function like sprintf
or format
is completely different and has nothing to do with binary operators. The key thing to note is that in those functions the %
character is part of a quoted string, and not a standard symbol on the command line (i.e. "%"
and %
are very different). In the context of sprintf
, inside a string, "%"
is a special character used to recognize that the subsequent characters have a special meaning and should not be interpreted as regular text. For example, in:
sprintf("I'm a number: %.2f", runif(3))
# [1] "I'm a number: 0.96" "I'm a number: 0.74" "I'm a number: 0.99"
"%.2f"
means a floating point number (f
) to be displayed with two decimals (.2
). Notice how the "I'm a number: "
piece is interpreted literally. The use of "%"
allows sprintf
users to mix literal text with special instructions on how to represent the other sprintf
arguments.
Use of $ and %% operators in R
You are not really pulling a value from a function but rather from the list object that the function returns. $
is actually an infix that takes two arguments, the values preceding and following it. It is a convenience function designed that uses non-standard evaluation of its second argument. It's called non-standard because the unquoted characters following $
are first quoted before being used to extract a named element from the first argument.
t.test # is the function
t.test(x) # is a named list with one of the names being "p.value"
The value can be pulled in one of three ways:
t.test(x)$p.value
t.test(x)[['p.value']] # numeric vector
t.test(x)['p.value'] # a list with one item
my.name.for.p.val <- 'p.value'
t.test(x)[[ my.name.for.p.val ]]
When you surround a set of characters with flanking "%"-signs you can create your own vectorized infix function. If you wanted a pmax
for which the defautl was na.rm=TRUE do this:
'%mypmax%' <- function(x,y) pmax(x,y, na.rm=TRUE)
And then use it without quotes:
> c(1:10, NA) %mypmax% c(NA,10:1)
[1] 1 10 9 8 7 6 7 8 9 10 1
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 do these operators mean (** , ^ , %, //)?
**
: exponentiation^
: exclusive-or (bitwise)%
: modulus//
: divide with integral result (discard remainder)
How to get help in R?
Getting help on a function that you know the name of
Use ?
or, equivalently, help
.
?mean
help(mean) # same
For non-standard names use quotes or backquotes; see An Introduction to R: Getting help with functions and features:
For a feature specified by special characters, the argument must be enclosed in double or single quotes, making it a “character string”: This is also necessary for a few words with syntactic meaning including
if
,for
andfunction
."
?`if`
?"if" # same
help("if") # same
There are also help pages for datasets, general topics and some packages.
?iris
?Syntax
?lubridate
Use the example
function to see examples of how to use it.
example(paste)
example(`for`)
The demo
function gives longer demonstrations of how to use a function.
demo() # all demos in loaded pkgs
demo(package = .packages(all.available = TRUE)) # all demos
demo(plotmath)
demo(graphics)
Finding a function that you don't know the name of
Use ??
or, equivalently, help.search
.
??regression
help.search("regression")
Again, non-standard names and phrases need to be quoted.
??"logistic regression"
apropos
finds functions and variables in the current session-space (but not in installed but not-loaded packages) that match a regular expression.
apropos("z$") # all fns ending with "z"
rseek.org
is an R search engine with a Firefox plugin.
RSiteSearch
searches several sites directly from R.
findFn
in sos
wraps RSiteSearch
returning the results as a HTML table.
RSiteSearch("logistic regression")
library(sos)
findFn("logistic regression")
Finding packages
available.packages
tells you all the packages that are available in the repositories that you set via setRepositories
. installed.packages
tells you all the packages that you have installed in all the libraries specified in .libPaths
. library
(without any arguments) is similar, returning the names and tag-line of installed packages.
View(available.packages())
View(installed.packages())
library()
.libPaths()
Similarly, data
with no arguments tells you which datasets are available on your machine.
data()
search
tells you which packages have been loaded.
search()
packageDescription
shows you the contents of a package's DESCRIPTION
file. Likewise news
read the NEWS
file.
packageDescription("utils")
news(package = "ggplot2")
Getting help on variables
ls
lists the variables in an environment.
ls() # global environment
ls(all.names = TRUE) # including names beginning with '.'
ls("package:sp") # everything for the sp package
Most variables can be inspected using str
or summary
.
str(sleep)
summary(sleep)
ls.str
is like a combination of ls
and str
.
ls.str()
ls.str("package:grDevices")
lsf.str("package:grDevices") # only functions
For large variables (particularly data frames), the head
function is useful for displaying the first few rows.
head(sleep)
args
shows you the arguments for a function.
args(read.csv)
General learning about R
The Info page is a very comprehensive set of links to free R resources.
Many topics in R are documented via vignette
s, listed with browseVignettes
.
browseVignettes()
vignette("intro_sp", package = "sp")
By combining vignette
with edit
, you can get its code chunks in an editor.
edit(vignette("intro_sp",package="sp"))
Node Sequelize find where $like wildcard
String operators (e.g. $operator
) is legacy in V5 of Sequelize [1].
You can still execute queries with operators the legacy way, but the connection has to be setup with aliases for operators (there will be a deprecation warning about this). [2]
const Op = Sequelize.Op;
const operatorsAliases = {
$like: Op.like,
$not: Op.not
}
const connection = new Sequelize(db, user, pass, { operatorsAliases })
[Op.like]: '%Bob%' // LIKE '%Bob%'
$like: '%Bob%' // same as using Op.like (LIKE '%Bob%')
The updated documentation for Sequelize.js
provides operators in the Sequelize.Op
module as Symbol operators. [3]
Sequelize uses Symbol operators by default to minimize the risk of operators injected in the query; it's advised to use Symbol operators going forward. [4]
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
let data: Array<any> = await MyDataSequelizeAccess.findAll({
where: {
name: {
[Op.like]: '%Bob%'
}
}
});
What is the meaning of int(a[::-1]) in Python?
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
Meaning of %o% in R
There are a number of shortcuts in R that use the %...%
notation. %o%
is the outer product of arrays
> 1:3 %o% 1:3
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
There are a number of others, my most used is %in%
:
3 %in% c(1,2,3,4) #TRUE
5 %in% c(1,2,3,4) #FALSE
3.4 %in% c(1,2,3,4) #FALSE
There are a few others, I don't know them all off the top of my head. But when you encounter them, you can check for documentation by using backticks around the %o%
like ?`%o%`
, or quotes ?'%o%'
(or ?"%o%"
).
They are obviously difficult to google because of the percent sign.
Why are there no ++ and -- operators in Python?
It's not because it doesn't make sense; it makes perfect sense to define "x++" as "x += 1, evaluating to the previous binding of x".
If you want to know the original reason, you'll have to either wade through old Python mailing lists or ask somebody who was there (eg. Guido), but it's easy enough to justify after the fact:
Simple increment and decrement aren't needed as much as in other languages. You don't write things like for(int i = 0; i < 10; ++i)
in Python very often; instead you do things like for i in range(0, 10)
.
Since it's not needed nearly as often, there's much less reason to give it its own special syntax; when you do need to increment, +=
is usually just fine.
It's not a decision of whether it makes sense, or whether it can be done--it does, and it can. It's a question of whether the benefit is worth adding to the core syntax of the language. Remember, this is four operators--postinc, postdec, preinc, predec, and each of these would need to have its own class overloads; they all need to be specified, and tested; it would add opcodes to the language (implying a larger, and therefore slower, VM engine); every class that supports a logical increment would need to implement them (on top of +=
and -=
).
This is all redundant with +=
and -=
, so it would become a net loss.
Related Topics
How to Generate Distributions Given, Mean, Sd, Skew and Kurtosis in R
Delete Columns/Rows with More Than X% Missing
Subset Based on Variable Column Name
How to Parse Year + Week Number in R
How to Create a "Macro" for Regressors in R
How to See Data from .Rdata File
Colorbar from Custom Colorramppalette
Is There a Vectorized Parallel Max() and Min()
How to Make Dodge in Geom_Bar Agree with Dodge in Geom_Errorbar, Geom_Point
How to Multiply Data Frame by Vector
Displaying a PDF from a Local Drive in Shiny
R Keep Rows with at Least One Column Greater Than Value
How to Save Data File into .Rdata
Efficient Row-Wise Operations on a Data.Table
Rstudio Not Picking the Encoding I'm Telling It to Use When Reading a File