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

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

On Fri, Dec 11, 2009 at 11:01 AM, William Dunlap <wdunlap at tibco.com> wrote:
>> -----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)})

Change my function to always returning one class may not always be
possible as I may call a third party R package that is not made by me
and does this kind of wired things of trying to 'simplify'. And I may
not know all the cases where the third party R package 'simplify' the
results, which does not always return the same type. In this case, I
can not be sure the return type is always the same. How do you deal
with this problem?

>> > 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]]
>> [[4]]
>> [1] 4
>> > apply(X,1, function(x) {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