R: What are operators like %in

前端 未结 4 1575
青春惊慌失措
青春惊慌失措 2020-12-02 13:46

I know the basics like == and !=, or even the difference (vaguely) between & and &&. But stuff like %in

4条回答
  •  醉酒成梦
    2020-12-02 14:14

    The R Language Definition, section 3.1.4 refers to them as "special binary operators". One of the ways they're special is that users can define new binary operators using the %x% syntax (where x is any valid name).

    The Writing your own functions section of An Introduction to R, refers to them as Binary Operators (which is somewhat confusing because + is also a binary operator):

    10.2 Defining new binary operators

    Had we given the bslash() function a different name, namely one of the form

    %anything%

    it could have been used as a binary operator in expressions rather than in function form. Suppose, for example, we choose ! for the internal character. The function definition would then start as

    > "%!%" <- function(X, y) { ... }

    (Note the use of quote marks.) The function could then be used as X %!% y. (The backslash symbol itself is not a convenient choice as it presents special problems in this context.)

    The matrix multiplication operator, %*%, and the outer product matrix operator %o% are other examples of binary operators defined in this way.

提交回复
热议问题