R function with no return value

后端 未结 5 431
滥情空心
滥情空心 2020-12-03 22:04

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 returni

5条回答
  •  离开以前
    2020-12-03 22:49

    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
    

提交回复
热议问题