[R] How to iteratively extract elements out of a list

Gabor Grothendieck ggrothendieck at gmail.com
Sun Aug 27 02:23:07 CEST 2006


On 8/26/06, Patrick Connolly <p_connolly at ihug.co.nz> wrote:
> On Sat, 26-Aug-2006 at 09:57AM +0100, Patrick Burns wrote:
>
> |>  > sub.m <- lapply(m, function(x)x[x>2])
> |>  > sub.m
> |> [[1]]
> |> [1] 3 4
> |>
> |> [[2]]
> |> [1] 4 5
> |>
> |> [[3]]
> |> [1] 4
> |>
> |>  > sub.m[unlist(lapply(sub.m, function(x) length(x) == 2))]
> |> [[1]]
> |> [1] 3 4
> |>
> |> [[2]]
> |> [1] 4 5
> |>
> |>  > sub4.m <- lapply(m, function(x)x[x>4])
> |>  > sub4.m[unlist(lapply(sub4.m, function(x) length(x) > 0))]
> |> [[1]]
> |> [1] 5
>
> Or slightly shorter in this case:
>
> sub.m[sapply(sub.m, function(x) length(x) == 2)]
>

or even shorter:

sub.m[sapply(sub.m, length) == 2]



More information about the R-help mailing list