[R] Why a list of NULL's are reduced to NULL?

William Dunlap wdunlap at tibco.com
Fri Dec 11 18:01:34 CET 2009


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Peng Yu
> Sent: Friday, December 11, 2009 8:44 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Why a list of NULL's are reduced to NULL?
> 
> The following examples are confusing to me. It is OK, to assigned NULL
> to one element in a list. The result is still a list. However, a list
> of NULL's are reduced to NULL. I don't understand how this conversion
> occurs. Could somebody let me know what is going on?

The "simplification" algorithm for reformatting
the output of apply and sapply is handy in the
common case when you know that FUN will return
the same sort of thing each time it it called.
The algorithm is not very useful when FUN may return
objects of various classes or lengths.  sapply has
a simplify=FALSE argument to avoid the simplification
(so it acts like lapply) but apply doesn't.

I suggest you either change your function to always
return one class and length of object or use lapply()
or sapply(simplify=FALSE,...) when you must use a function
with variable output type.  E.g., instead of
   apply(X, 1, function(row){f(row)})
use
   lapply(seq_len(nrow(X)), function(rowIndex){f(X[rowIndex,])})
or
   lapply(split(X, row(X)), function(row){f(row)})

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> 
> > X=matrix(1:8, nr=4)
> > apply(X,1, function(x) {if(x[[1]]==3){NULL}else{x[[1]]}})
> [[1]]
> [1] 1
> 
> [[2]]
> [1] 2
> 
> [[3]]
> NULL
> 
> [[4]]
> [1] 4
> 
> > apply(X,1, function(x) {NULL})
> NULL
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 




More information about the R-help mailing list