Seydou GORO
Seydou GORO

Reputation: 1285

How to apply if statement to a list

I have a list of 4 vectors

Z has no element inside it.

 liste<-list(A=c(1),B=c(1,2),C=c(1:3),Z=character(0))

lapply(liste, length)

$A
[1] 1

$B
[1] 2

$C
[1] 3

$Z
[1] 0

I would like to recreate a list with only vectors that have a non-zero length.

   $A
[1] 1

$B
[1] 1 2

$C
[1] 1 2 3

Upvotes: 1

Views: 103

Answers (2)

akrun
akrun

Reputation: 887851

We can use Filter wrapped along with lapply.

lapply(Filter(length, liste), length)

The length returns 0 for the character(0) and it is changed to logical i.e. FALSE and all values greater than 0 as TRUE to Filter those elements, then get the length


A more efficient and vectorized option is lengths

liste[lengths(liste) > 0]

EDIT: based on @Waldi comments

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

I think the Filter approach by @akrun is the most elegant so far. Here is another one but with subset + lengths

> subset(liste, !!lengths(liste))
$A
[1] 1

$B
[1] 1 2

$C
[1] 1 2 3

Upvotes: 1

Related Questions