[Rd] assigning NULLs to elements of a list

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Feb 12 12:52:30 CET 2008


On Tue, 12 Feb 2008, 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?

Yes, it was apparently intended: R has long done this.

x <- list(a=c(1L,2L), b=matrix(runif(4),2,2), c=LETTERS[1:3])
x[2] <- list(NULL)

is what I think you are intending.

See e.g. the comment in subassign.c

 	    /* If "val" is NULL, this is an element deletion */
 	    /* if there is a match to "nlist" otherwise "x" */
 	    /* is unchanged.  The attributes need adjustment. */


>
> 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
> 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
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list