Is there a difference between assigning value using '-' or '=' in R?

8

In practical terms there seems to be no difference, but underneath the cloth as the language processes is there any difference?

    
asked by anonymous 20.10.2016 / 01:17

2 answers

6

Complementing Marcus's answer. An interesting point is the precedence of these operators. <- comes before = . What causes:

> a <- b = 1
Error in a <- b = 1 : não foi possível encontrar a função "<-<-"

Do not work, but:

> a = b <- 1
> a
[1] 1
> b
[1] 1

Run.

This is the only case I've seen that gives an error ... But as it is very unusual, it ends up whatever it is used for.

In fact, I just saw that this example is in the pecedence link .

## '=' has lower precedence than '<-' ... so you should not mix them
##     (and '<-' is considered better style anyway):
## Consequently, this gives a ("non-catchable") error
 x <- y = 5  #->  Error in (x <- y) = 5 : ....

If you link to code style, most books recommend using <- . Example:

Advance R

  

Assignment Use

20.10.2016 / 12:51
7

There is no difference in the vast majority of cases. The commands

x <- 5

and

x = 5

are identical.

However, if you want to assign arguments to a function, you are required to use = . For example, to generate a sample of 10 observations of a normal random variable with mean 5 and standard deviation 2, only the

rnorm(10, mean = 5, sd = 2)

It works. It's no use trying to run

rnorm(10, mean <- 5, sd <- 2)

You will not get the desired result.

In particular, I'd rather use <- whenever I'm going to assign some value to an object. I find it more elegant because it differs from assigning arguments to functions. But it's just a matter of style.

    
20.10.2016 / 01:42