2

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.

Community
  • 1
  • 1
probaPerception
  • 581
  • 1
  • 7
  • 19

2 Answers2

4

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.

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • It sounds even more weird for me. I'll use this method now, thanks. Why is that? Does anyone has any idea of the reason why "{ ... }" makes the code working? Thanks – probaPerception Nov 19 '12 at 17:18
  • 4
    it's because you are telling the parser that you want it to assign values to an object, rather than creating a list to pass to a function. – Andrie Nov 19 '12 at 17:20
  • 9
    Or better yet start using `<-` for assignment! – Dason Nov 19 '12 at 17:27
1

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!

Steve Pitchers
  • 7,088
  • 5
  • 41
  • 41