[R] NULL object, R programming

Marc Schwartz MSchwartz at medanalytics.com
Fri Feb 28 04:47:03 CET 2003


Makram Talih wrote:
> Dear R users,
> 
> I get the following (I think puzzling) result when doing the following:
> 
> 
>>a <- list(3,4,5)
>>a[[2]] <- NULL
>>a
> 
> [[1]]
> [1] 3
> 
> [[2]]
> [1] 5
> 
> I would have expected the result to be:
> 
> [[1]]
> [1] 3
> 
> [[2]]
> NULL
> 
> [[3]]
> [1] 4
> 
> as in the outcome of:
> 
> 
>>list(3, NULL, 4)
> 
> 
> Is this a desired effect? If so, could it be built in a 'help(NULL)' file?
> 
> If you think it is relevant, I am using the following R version:
> 
> platform i386-pc-mingw32
> arch     i386           
> os       mingw32        
> system   i386, mingw32  
> status                  
> major    1              
> minor    6.2            
> year     2003           
> month    01             
> day      10             
> language R  
> 
> 
> Many thanks for any clarifications regarding this!
> 
> Regards,
> 
> Makram Talih
> Yale University
> Statistics

That behavior is documented in R FAQ 7.3:

"7.3 How can I set components of a list to NULL?

You can use

x[i] <- list(NULL)

to set component i of the list x to NULL, similarly for named 
components. Do not set x[i] or x[[i]] to NULL, because this will remove 
the corresponding component from the list.

For dropping the row names of a matrix x, it may be easier to use 
rownames(x) <- NULL, similarly for column names."


Change your code sequence to:

 > a <- list(3,4,5)
 > a[2] <- list(NULL)
 > a
[[1]]
[1] 3

[[2]]
NULL

[[3]]
[1] 5


HTH,

Marc Schwartz




More information about the R-help mailing list