0

I would like to create a function with the percentage sign in r. Something similar to the pipe operator in magrittr ($>$).

Here the code

%|%(x) <- function(x){...}

Unfortunately I received the following error:

Error: unexpected SPECIAL in "%|%"

Is there anything I am missing? Thank you for your help

1 Answers1

1

Syntactically invalid names need to be wrapped in backticks (`…`) to be used in code. This includes operators when using them as regular R names rather than infix operators. This is the case when you want to define them:

`%|%` <- function(a, b) a + b

It’s also the case when you want to pass them into a higher-order function such as sapply:

sapply(1 : 5, `-`)
# [1] -1 -2 -3 -4 -5

(Of course this particular example is pretty useless since most operators are vectorised so you could just write - (1 : 5) instead of the above.)

You might also see code that uses quotes instead of backticks but this is discouraged.

Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183