CHRD
CHRD

Reputation: 1957

Delete list conditional on the number of elements in R

I have a list L of unnamed comma separated character lists. Each list of characters is of unequal length. I need to drop the character lists that have less than 4 elements from L. How can this be done? Example L:

> L
[[1]]
[1] "A" "B" "C" "D"
[[2]]
[1] "E" "F" "G" 

In the example above I would like to end up with:

> L
[[1]]
[1] "A" "B" "C" "D"

Upvotes: 3

Views: 2410

Answers (1)

akrun
akrun

Reputation: 886948

We can use lengths to get the length of the list elements as a vector, create a logical vector based on that and subset the list

L[lengths(L)>3]
#[[1]]
#[1] "A" "B" "C" "D"

A less optimized approach (used earlier) is to loop through the list elements with sapply, get the length and use that to subset

L[sapply(L, length)>3]

data

L <- list(LETTERS[1:4], LETTERS[5:7])

Upvotes: 5

Related Questions