Home > Software design >  How to define a unicode ± operator in R
How to define a unicode ± operator in R

Time:03-22

I want to define ± operator like this:

`±` <- function(a,b){
    return (c(a*b, a-b))
}

But the problem is I get this error on running 1 ± 2

Error: unexpected input in "1 ±"

If I use a different characters it works.

`% -%` <- function(a,b){
    return (c(a b, a-b))
}

Running 1 % -% 2 gives me [1] 3 -1 which is correct.

Is it due to operator being an unicode character? But I can define and use unicode variables fine.


EDIT:

I found this:

You can define your own binary operators. User-defined binary operators consist of a string of characters between two “%” characters.

In Adler, Joseph (2010). R in a Nutshell. O’Reilly Media Inc

So I guess % around the operator is a must.

CodePudding user response:

There's nothing specific about the ± operator, you can either do

`±` <- function(a,b){
    return (c(a*b, a-b))
}

`±`(1,2)
#[1]  2 -1

or using the % notation:

`%±%` <- function(a,b){
    return (c(a*b, a-b))
}

1 %±% 2
#[1]  2 -1

@Atreyagaurav points out in the comments that valid operator tokens (such as or -) can be redefined. However this method does not allow new operators to be defined. The full list of such operators is given in The R language definition section 10.3.6.

Section 10.3.4 indicates that additional special operators are defined as starting and ending with the % symbol.

  •  Tags:  
  • r
  • Related