[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:36:59 CET 2009
On Fri, Dec 11, 2009 at 11:27 AM, Steve Lianoglou
<mailinglist.honeypot at gmail.com> wrote:
> Hi,
>
> On Dec 11, 2009, at 12:07 PM, Peng Yu wrote:
>
>> 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.
>
> You're right, x[i] is not the same as x$a_name:
>
> R> x <- list(a=1:3, b='hello')
> R> identical(x[1], x$a)
> [1] FALSE
>
> R> identical(x[1], x['a'])
> [1] TRUE
>
> I think that's what it means by "similarly for named components." You see, x$a_name is really x[[1]], which does the destructive-null-assignment-thing:
>
> R> identical(x[[1]], x$a)
> [1] TRUE
>
> -steve
>
>
>> 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?
Do you have any comments on the above question?
More information about the R-help
mailing list