Arrinao
Arrinao

Reputation: 47

Difference between function(x) and function()x

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.

Upvotes: 2

Views: 132

Answers (1)

Sathish
Sathish

Reputation: 12713

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

Upvotes: 3

Related Questions