Home > other >  Using R, can I create special functions like %in% just one input (LEFT) or (RIGHT)?
Using R, can I create special functions like %in% just one input (LEFT) or (RIGHT)?

Time:09-03

The common notation for factorial is the ! operator in mathematics.

I can create function:

"%!%" = function(n, r=NULL) { factorial(n); }

This works as expected if I pass a NULL or NA to the RHS, which I don't really want to do.

3 %!% NA

3 %!% NULL

3 %!% .

What I would like to do is just enter:

3 %!%

Any suggestions on HOW I can do that? In that setup, I want the LHS (left) to be the input and the RHS (right) to be ignored.

I can do the BOTH no problem:

nPr = function(n, r, replace=FALSE) 
    { 
    if(replace) { return( n^r ); }
    factorial(n) / factorial(n-r); 
    }
"%npr%" = "%nPr%" = nPr;

nCr = function(n, r, replace=FALSE) 
    { 
    # same function (FALSE, with n r-1)
    if(replace) { return( nCr( (n r-1), r, replace=FALSE ) ); } 
    factorial(n) / ( factorial(r) * factorial(n-r) ); 
    }
"%ncr%" = "%nCr%" = nCr;

where

5 %nCr% 3
5 %nPr% 3

work as expected based on selection without replacement.

Question: How to use the special operator with just the LHS?

The follow-on question is the opposite. Let's say I want the LHS (left) to be ignored and focus on the RHS (right). I believe this is how the built-in ? function links to help and ?? links to help.search(). Let's say I wanted to create an %$$% operator that worked that way.

CodePudding user response:

No, you can't do that. The %any% operators are defined by the parser to be binary operators.

You can see all of the operators in R in the ?Syntax help page. Some are binary, some are unary, and some can be either one, but the unary operators always precede the argument. You can attach different functions to most of them (e.g. change the meaning of ! in !x), but you can't change the parser to allow x! to be legal code.

  • Related