[R] The correct way to set an element in a list to NULL? (FAQ is not clear)

Peng Yu pengyu.ut at gmail.com
Fri Dec 11 18:07:40 CET 2009


http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-set-components-of-a-list-to-NULL_003f

The explanation on this FAQ entry is not clear. It says '... similarly
for named components...'. What I understood was x[i]<-list(NULL) is
the same as x$a_name<-list(NULL). But, they are not. As the example
below shows, x$a_name<-list(NULL) is the same as x[[i]]<-list(NULL).

> x=list(a=1:3,b=NULL,c=2:5,d=NULL)
> x
$a
[1] 1 2 3

$b
NULL

$c
[1] 2 3 4 5

$d
NULL

> x[[3]]=list(NULL)
> x
$a
[1] 1 2 3

$b
NULL

$c
$c[[1]]
NULL


$d
NULL

> x$c=list(NULL)
> x
$a
[1] 1 2 3

$b
NULL

$c
$c[[1]]
NULL


$d
NULL

>
> x[[3]]=7:8
> x
$a
[1] 1 2 3

$b
NULL

$c
[1] 7 8

$d
NULL

> x$c=7:8
> x
$a
[1] 1 2 3

$b
NULL

$c
[1] 7 8

$d
NULL


What seems confusing to me is:
even 'x[i]<-list(NULL)' and 'x[[i]]<-list(NULL)' are different, why
x[i]<-NULL and x[[i]]<-NULL are the same?

Shouldn't the meaning of 'x[[i]]<-NULL' be defined as the set the i'th
element NULL, rather than deleting the i'th element?




More information about the R-help mailing list