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

Marc Schwartz marc_schwartz at me.com
Fri Dec 11 05:00:17 CET 2009


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

HTH,

Marc Schwartz




More information about the R-help mailing list