Why should the operator "=" R not be used in functions?

The manual states:

The operator '<- can be used anywhere, while the operator' = is allowed only at the top level (for example, in the full expression entered on the command line) or as one subexpression in the extended list of expressions.

The question here mentions the difference when using a function call. But in the function definition, it works fine:

a = function () { b = 2 x <- 3 y <<- 4 } a() # (b and x are undefined here) 

So, why does the manual mention that the operator '=' is only allowed at the top level ??

There is no description in the description (no operator = , what a shame!)

+6
source share
3 answers

The text you are quoting says at the top level OR in a braced list of subexpressions . You use it in the extended list of subexpressions. It is allowed.

You need to go very long to find an expression that is neither full nor braces. Here is one. Sometimes you want to bind the assignment inside the try: try( x <- f() ) block try( x <- f() ) in order, but try( x = f(x) ) not - you need to either change the assignment operator or add curly braces.

+12
source

Non-top-level expressions include use in control structures such as if . For example, the following programming error is illegal.

 > if(x = 0) 1 else x Error: syntax error 

As mentioned here: fooobar.com/questions/15764 / ...

Also see http://developer.r-project.org/equalAssign.html

+7
source

Besides some examples, such as system.time , as others have shown, where <- and = have different results, the main difference is more philosophical. Larry Wall, the creator of Perl, said something like “similar things should look the same, different things should look different”, I found it interesting in different languages ​​to see that things are considered “similar” and which are considered “ similar, "different." Now, to assign R, you can compare 2 commands:

 myfun( a <- 1:10 ) myfun( a = 1:10 ) 

Some argue that in both cases we assign 1:10 to a , so we do the same.

Another argument is that in the first call, we assign the variable a , which is in the same environment from which myfun is myfun , and in the second call, we assign the variable a , which is in the environment created when the function is called and is local to the function , and those two variables a are different.

So what to use depends on whether you think the assignments are "similar" or "different."

Personally, I prefer <- , but I don’t think it’s worth fighting the holy war.

+3
source

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


All Articles