Search code examples
rassignment-operator

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.


Solution

  • 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!