[Rd] assigning NULLs to elements of a list

Dan Davison davison at stats.ox.ac.uk
Tue Feb 12 12:52:43 CET 2008


On Tue, Feb 12, 2008 at 11:06:59AM +0000, Oleg Sklyar wrote:
> Dear developers:
> 
> I have just came across an (unexpected to me) behaviour of lists when 
> assigning NULLs to list elements. I understand that a NULL is a valid R 
> object, thus assigning a NULL to a list element should yield exactly the 
> same result as assigning any other object. So I was surprised when 
> assigning a NULL in fact removed the element from the list. Is this an 
> intended behaviour? If so, does anybody know where is it documented and 
> what is a good way around?
> 
> Thanks for help,
> Oleg Sklyar
> 
> Here goes an example, the inline C-code does exactly what I would prefer 
> R were doing, but both R examples do remove the element 'b':
> 
> x = list(a=c(1L,2L), b=matrix(runif(4),2,2), c=LETTERS[1:3])
> 
> library(inline)
> code="
>    SEXP res;
>    PROTECT(res = Rf_duplicate(x));
>    SET_VECTOR_ELT(res,1,R_NilValue);
>    UNPROTECT(1);
>    return res;
> "
> setnull = cfunction(signature(x="list"),code)
> setnull(x)
> 
> # $a
> # [1] 1 2
> # $b
> # NULL
> # $c
> # [1] "A" "B" "C"
> 
> y = x
> x[[2]] = NULL

Hi Oleg,

To do this I use

x[2] <- list(NULL)

In particular I do this when constructing lists to act as the 'what' argument for scan(), where
a NULL element means that the column should be skipped, whereas obviously a non-existent element
won't serve that purpose. I would be interested to hear whether this is the 'proper' way to construct
such lists.

Dan



> x
> # $a
> # [1] 1 2
> # $c
> # [1] "A" "B" "C"
> 
> x = y
> x$b = NULL
> x
> # $a
> # [1] 1 2
> # $c
> # [1] "A" "B" "C"
> 
>  > sessionInfo()
> R version 2.6.1 (2007-11-26)
> i686-pc-linux-gnu
> 
> locale:
> LC_CTYPE=en_GB.UTF-8;LC_NUMERIC=C;LC_TIME=en_GB.UTF-8;LC_COLLATE=en_GB.UTF-8;LC_MONETARY=en_GB.UTF-8;LC_MESSAGES=en_GB.UTF-8;LC_PAPER=en_GB.UTF-8;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_GB.UTF-8;LC_IDENTIFICATION=C
> 
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
> 
> other attached packages:
> [1] inline_0.3.3
> 
> loaded via a namespace (and not attached):
> [1] rcompgen_0.1-17
> 
> 
> -- 
> Dr Oleg Sklyar * EBI-EMBL, Cambridge CB10 1SD, UK * +44-1223-494466
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



More information about the R-devel mailing list