Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create "missing objects" (aka: "empty symbols" , "empty objects") / needed for formals manipulation/

Tags:

r

How to create an "empty object" in R? [edit: I don't know how to rightly call this "thing" so I am calling it "empty object", others: "empty symbol", "zero length symbol", "missing object" might also be used]

[edit2: finally I tend to settle down on the "missing symbol object" for the name of the "thing". It also appears that J.Chambers is using this terminology in his 2008 book, see comments for @mbq's answer. According to Chambers, the "missing symbol" has a zero-length string as it's contents. Thus, as.symbol("") should create such an object, which it doesn't in current version of R(2.11.1) ]

The simplest way I could find is

x <- alist(a=)$a

[Clarification]

Note that "empty object" is not a NULL object or a vector of length 0. "Empty object" x in my above example could be used in the function's formals manipulation, which is what I need it for.

Here is an example:

> al <- alist(a = 323, b = , c = 434)  
> al  
$a  
[1] 323  
$b  
$c  
[1] 434  

>   
> al[["c"]] <- numeric()  
> al  
$a  
[1] 323  
$b  
$c                                   #not empty  
numeric(0)  

>   
> al[["c"]] <- list()              
> al  
$a  
[1] 323  
$b  
$c                                   #not empty  
list()  

>   
>   
> al[["c"]] <- NULL                    #object removed  
> al  
$a  
[1] 323  
$b  


>   
> al[["c"]] <- alist(a = )$a  
> al  
$a  
[1] 323  
$b  
$c                                      #empty  

So, I am just looking for a way to create empty objects for use in function's formals manipulations. I am pretty sure there must be a way in base R.

Here is an example:

> foo <- function(a = 3232, b = 234){b+a}  
> formals(foo)  
$a  
[1] 3232  

$b  
[1] 234  

> formals(foo)$c <- alist(a = )$a  
> formals(foo)  
$a  
[1] 3232  

$b  
[1] 234  

$c  


> foo <- function(a = 3232, b = 234){b+a}  
> formals(foo)  
$a  
[1] 3232  

$b  
[1] 234  

> formals(foo)$c <- alist(a = )$a  
> formals(foo)  
$a  
[1] 3232  

$b  
[1] 234  

$c  

Thanks.

like image 652
VitoshKa Avatar asked Oct 08 '10 16:10

VitoshKa


2 Answers

Try substitute():

foo <- function(a = 3232, b = 234) {}
formals(foo)$c <- substitute()
foo
# function (a = 3232, b = 234, c)
like image 128
hadley Avatar answered Nov 19 '22 09:11

hadley


What have you done with alist(a=)$a is not an empty object, it is empty symbol/name ('' compiled as symbol name). I'm pretty sure it can't be replicated in any other way (as.symbol('') raises error).

like image 31
mbq Avatar answered Nov 19 '22 09:11

mbq