[R] How to get rid of NULL in the result of apply()?

Peng Yu pengyu.ut at gmail.com
Fri Dec 11 05:58:11 CET 2009

```On Thu, Dec 10, 2009 at 10:00 PM, Marc Schwartz <marc_schwartz at me.com> wrote:
> On Dec 10, 2009, at 9:44 PM, Peng Yu wrote:
>
>> The following code returns a list with the 2nd element as NULL. I'm
>> wondering what the best way to get rid of NULL element in an
>> 'apply()'s result.
>>
>>> lapply(1:3, function(x) {
>>
>> +       if(x==2) {
>> +         return(NULL)
>> +       } else {
>> +         return(x)
>> +       }
>> +     }
>> +     )
>> [[1]]
>> [1] 1
>>
>> [[2]]
>> NULL
>>
>> [[3]]
>> [1] 3
>
>
> L <- list(1, NULL, 3)
>
>> L
> [[1]]
> [1] 1
>
> [[2]]
> NULL
>
> [[3]]
> [1] 3
>
>
> L[[2]] <- NULL
>
>> L
> [[1]]
> [1] 1
>
> [[2]]
> [1] 3
>
>
> The above is actually covered in the first R FAQ:
>
> http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-set-components-of-a-list-to-NULL_003f

Is there a version of apply that returns a list without NULL's?

I try to remove NULL elements in the following example, but neither
for loops work. Would you please let me know what the correct way is?

x=list(a=1:3,b=NULL,c=2:5,d=NULL)
x
for(i in seq(along=x)) {
if(length(x[[i]])==0) {
x[[i]]=NULL
}
}

for(i in seq(along=x)) {
if(x[[i]]==NULL) {
x[[i]]=NULL
}
}

```