probaPerception
probaPerception

Reputation: 591

the difference between = and <- operator in the function system.time()

I am using the function system.time() and I have discovered something which surprises me. I often use the allocation symbol “=” instead of “<-”. I am aware most R users use “<-” but I consider “=” clearer in my codes. Thus, I used “=” to allocate a value in a function system.line() and the following error message appeared : Error: unexpected '=' in "system.time(a[,1] ="

Here is the code :

a = matrix(1, nrow = 10000)

require(stats)
system.time(a[,1] = a[,1]*2) #this line doesn't work 
#Error: unexpected '=' in "system.time(a[,1] ="
system.time(a[,1] = a[,1]*2) #this line works
system.time(for(i in 1:100){a[,1] = a[,1]*i}) #this line works!!!!

I found : Is there a technical difference between "=" and "<-" which explains that I can’t use “=” in a function to allocate since it is the symbol to assign argument in a function. But I have been surprised to see that it can work sometimes (see following code).

Does anyone know why it works here? (also why it doesn't work in the first case since I guess, a[,1] is not a parameter of the function system.time()...)

Thank you very much. Edwin.

Upvotes: 2

Views: 380

Answers (2)

Steve Pitchers
Steve Pitchers

Reputation: 7364

In system.time(a[,1] = a[,1]*2) the equals sign does not mean assignment, it is interpreted as an attempt to bind a "named argument"; but system.time does not have an argument of that name.

In system.time(for(i in 1:100){a[,1] = a[,1]*i}) the equals sign really is doing an assignment; and that works fine.

If you wrote system.time(a[,1] <- a[,1]*2) the <- can only mean assignment, not argument binding, and it works!

But beware! If you wrote system.time(a[,1] < - a[,1]*2), it also "works" but probably doesn't do what you meant!

Upvotes: 1

Andrie
Andrie

Reputation: 179558

Wrap your code in { ... } braces and it will work:

system.time({a[,1] = a[,1]*2})
   user  system elapsed 
      0       0       0 

From ?"<-"

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

Upvotes: 4

Related Questions