In R, how to get the whole command line in sys.call () of a binary operator?

I wrote a binary operator function for R (that is, one with a name like %X% , so instead of typing %X%(a,b) , I can use the more convenient syntax a %X% b . My goal is to have a wrapper for <- which does things like a log of what was done with objects in this environment, and check the "protected" attribute, which would warn the user before overwriting this object.

All this works, except if I try to do something like a %X% b + c inside a function, all you see is a %X% b _and, and that’s all it does; a gets the value of b, and c is completely ignored. a %X% (b + c) works, etc. %X%(a, b + c) , but the whole point of writing this binary operator is to avoid parentheses.

If I overwrite <- , its sys.call() sees everything left and right of it. Why are mine only seeing contiguous names on the command line?

Here is the code that replicates this problem:

 `%X%` <- function(...){ print(deparse(sys.call())); } a %X% 3 + 1:10; 

Desired result: "% X% 3 + 1:10" Observed result: "% X% 3"

Thanks.

+6
source share
2 answers

I believe there is no way to lower the priority of a user statement. However, I think I found a crappy workaround: I can name my operator <<-

I really don’t understand how dispatching <- works, and there must be dozens for different object-oriented methods <- (none of which are displayed in methods( <- ) . I know that when I redefine <- , all kinds of things break .

However, <<- has a priority close to priority <- and this is not particularly useful, because for the occasional case when you really need to write a global variable from within a function or loop, you can simply use .GlobalEnv[['foo']] <- bar or assign('foo',bar,env=.GlobalEnv) .

In addition, since I am only trying to write and write protection objects in .GlobalEnv in the first place, the new value that I assign <<- is even somewhat consistent with the original one.

+2
source

This is due to operator precedence, see ?Syntax for more help. It says that special operators ( %any% ) like the ones you are trying to define take precedence over binary + , so there’s no other way (AFAIK) for you to use parentheses and do a %X% (b + c) .

+6
source

Source: https://habr.com/ru/post/922135/


All Articles