3

I'm assigning values within the output list of a function, like:

nofun = function(sth){

something happening here

metrics = list(
metric1 = value1
metric2 <- value2 )

return(metrics)
}

Once I query metrics, I noticed that the use of <- and = differs: the first ones only assigns the value to a variable with no name (i.e. "x1"= value1), while the second one applies also the correct name (i.e. metric1 = value1).

This behaviour is cited also for data.frame at the bottom of an old more generic question, but there is no explanation of this specific usage case.

It caused me quite many headaches and waste of time before noticing it, but I didn't find any other useful information. thanks in advance!

Nico
  • 191
  • 1
  • 6
  • Possible duplicate of [What are the differences between "=" and "<-" in R?](https://stackoverflow.com/questions/1741820/what-are-the-differences-between-and-in-r) – heds1 Jun 22 '19 at 21:42

1 Answers1

2

To define a named list you have to use the syntax list(name1 = value1, name2 = value2, ...). Elements of the list defined in this way have an attribute name containing their name.

Writing name2 <- value2 assigns value2 to a variable name2. If you write this inside of a list definition (list(name2 <- variable2)) the variable is included in the list but no name attribute is defined. So it is equivalent to:

name2 <- variable2
list(name2)

You can compare both statements:

attributes(list(a=3))
# $names
# [1] "a"
attributes(list(a<-3))
# NULL
jkd
  • 1,327
  • 14
  • 29
  • oh, great! so, the simple reason why this happens is because it is a *rule*. So, as a rule of thumb, using "=" can be considered the best option for assigning values during the contruction of an object (data.frame/list/whatever)? – Nico Jun 22 '19 at 22:29
  • Exactly, inside of a function (except `<-` which is also a function itself) always use `=`. – jkd Jun 22 '19 at 22:33