Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The arcane formals(function(x){})$x

What is the object formals(function(x){})$x?

It's found in the formals of a function, bound to arguments without default value.

Is there any other way to refer to this strange object? Does it have some role other than representing an empty function argument?

Here are some of its properties that can be checked in the console:

> is(formals(function(x){})$x)
[1] "name"      "language"  "refObject"
> formals(function(x){})$x

> as.character(formals(function(x){})$x)
[1] ""

EDIT: Here are some other ways to get this object:

alist(,)[[1]]
bquote()
quote(expr=)
like image 320
Ferdinand.kraft Avatar asked May 24 '13 17:05

Ferdinand.kraft


1 Answers

Background: What is formals(function(x) {})?

Well, to start with (and as documented in ?formals) , formals(function(x) {}) returns a pairlist:

is(formals(function(x){}))
# [1] "pairlist"

Unlike list objects, pairlist objects can have named elements that contain no value -- a very nice thing when constructing a function that has a possibly optional formal argument. From ?pairlist:

tagged arguments with no value are allowed whereas ‘list’ simply ignores them.

To see the difference, compare alist(), which creates pairlists, with list() which constructs 'plain old' lists:

list(x=, y=2)
# Error in list(x = , y = 2) : argument 1 is empty

alist(x=, y=2)
# $x
# 
# $y
# [1] 2

Your question: What is formals(function(x) {})$x?

Now to your question about what formals(function(x) {})$x is. My understanding is in some sense its real value is the "empty symbol". You can't, however, get at it from within R because the "empty symbol" is an object that R's developers -- very much by design -- try to entirely hide from R users. (For an interesting discussion of the empty symbol, and why it's kept hidden, see the thread starting here).

When one tries to get at it by indexing an empty-valued element of a pairlist, R's developers foil the attempt by having R return the name of the element instead of its verbotten-for-public-viewing value. (This is, of course, the name object shown in your question).

like image 106
Josh O'Brien Avatar answered Oct 09 '22 03:10

Josh O'Brien