R function with no return value

function, r

Solution

You need to understand the difference between a function returning a value, and printing that value. By default, a function returns the value of the last expression evaluated, which in this case is the assignment

arg <- arg + 3

(Note that in R, an assignment is an expression that returns a value, in this case the value assigned.) This is why `data <- derp(500)` results in `data` containing 503.

However, the returned value is not printed to the screen by default, unless you isolate the function's final expression on its own line. This is one of those quirks in R. So if you want to see the value:

derp <- function(arg)
{
    arg <- arg + 3
    arg
}

or just

derp <- function(arg)
arg + 3

Problem

I was helping a friend of mine with some of his code. I didn't know how to explain the strange behavior, but I could tell him that his functions weren't explicitly returning anything. Here is a minimum reproducible example: ``` derp <- function(arg){ arg <- arg+3 } data <- derp(500) data #[1] 503 derp(500) #nothing outputs class(derp(500)) #[1] "numeric" ``` Is there a name for this that I can google? Why is this happening? Why isn't arg being destroyed after the call to derp() finishes?

Original source

Related problems