Reputation: 79
I'm trying to understand this:
'%!in%' <- function(x,y)!('%in%'(x,y))
Is '%!in%'
just the name of the function? What are the uses/benefits of giving a function a name like this?
What role does !('%in%'(x,y))
play in the function?
Upvotes: 0
Views: 83
Reputation: 545766
The use of naming a function like %…%
is that it can be used as an infix operator:
4 %in% (1 : 10)
# TRUE
4 %!in% (1 : 10)
# FALSE
Since %…%
isn’t a valid name, it needs to be backtick-quoted (with `…`
) when used as a name (e.g. when defining it or when using it as a regular function):
# Definition:
`%!in%` = function (x, y) ! x %in% y
# Using function call syntax
`%in%`(4, 1 : 10)
# Passing it to a different function
lapply(c(2, 4, 20), `%in%`, 1 : 10)
For historical reasons/backwards compatibility, R also allows you to use regular quotes ('…'
or "…"
) instead of backticks in specific situations. However, this usage is confusing and not recommended!
Upvotes: 4