Search code examples
rreturnvariable-assignment

variable-assignment: Difference between "<-" and "=" in a certain post & avoiding using "return"


I have found the following solution on here about the post: https://stackoverflow.com/a/34327262/2994949

The user eipi10 uses = insted of <- to assign a value to the corrFunc function. Why does he do this?

Also, he/she creates the data.frame in the next line, but does not use a return to have that data.frame returned from the code. The function works, so I wonder why and how.

EDIT Does it provide any advantages to used or not to use the returncommand? This is something that has not been answered before, that's why I think this is not a duplicate.

I tried to ask this in a comment, but I need 50 reputation to put comments and why I put an answer in the initial thread, it was immediately deleted. Could anybody tell me, how to ask about a solution I find in a thread when I can not comment and can not post an answer?

Thank you.

EDIT

The first part of my question has been answered partly by the link but I still do not understand why the return is avoided. thanks :)


Solution

  • From ?return:

    If the end of a function is reached without calling return, the value of the last evaluated expression is returned.

    For example,

    f <- function() {
       x <- 1
       x
    }
    

    is equivalent to the same function with return(x) as the last statement. Perhaps surprisingly,

    f <- function() {
       x <- 1
    }
    

    also returns the same value, but returns it invisibly. There is a minor schism (perhaps not quite as strong as the = vs. <- schism) about whether it's better practice to always use an explicit return(): I believe it is good practice (because it makes the intention of the code more explicit), but many old-school R programmers prefer the implicit return value.