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!

1

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

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)?
Exactly, inside of a function (except <- which is also a function itself) always use =.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.