Difference between function(x) and function()x

Viewed 82

The title. I would especially want to know how the second one works. I know this is mostly used with getters so it retrieves a value, but I would like to know the inner mechanism and how to work with it.

1 Answers

function(x):

x is the argument of the function. For example:

myFun <- function(x) {print(x)}
myFun(x = 3)  # you are passing a value 3 to the argument x, which is printed inside the function.
# [1] 3

function()x

There is no argument in this function. But inside the function, it retrieves the value of x from the scope above it.

x <- 2
myFun <- function() x
myFun()
# [1] 2
Related