1

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.

Atreyagaurav
  • 1,145
  • 6
  • 15
  • 1
    Your second example works because you're using `%` symbols, not because it's a different character – Miff Mar 21 '22 at 15:59

1 Answers1

3

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.

Miff
  • 7,486
  • 20
  • 20
  • It works when called like `\`±\`(1,2)` but it doesn;t when I call it like `1 ± 2` – Atreyagaurav Mar 21 '22 at 15:54
  • I don't believe it's possible to define arbitrary characters as binary operators like that with any symbol, which is why the `%` notation was introduced – Miff Mar 21 '22 at 15:57
  • Interesting, when I searched how to define operators I saw the examples with `%..%` But none of them said anything about it being a must. So I thought it was a convention. Specially since `+` or `-` can be redefined with a function. It feels odd that `\`±\`(1,2) ` works but not `1±2`. – Atreyagaurav Mar 21 '22 at 16:02
  • @Atreyagaurav R function names are supposed to start with letters or periods unless escaped. The %op% conventions is for defining binary operators. Surely would would need to use `\`±\`` (with backticks which are problematic in comments on SO but escaping with backslash seems to work here) instead of a naked ± if you had first defined an S4 method for that symbol. Might be possible. You might need to assign it to the `Arith` group of operators. See `?Arith` and follow lots of the links to S4 related functions. Defining S4 methods is not for the faint of heart. – IRTFM Mar 22 '22 at 00:36
  • Possibly useful: https://stackoverflow.com/questions/66436990/group-generic-methods-for-ops-for-time-series – IRTFM Mar 22 '22 at 00:46