branch.lizard
branch.lizard

Reputation: 595

Extract Names from List using If Then Statements

Given the list below, I would like to extract the names of each sublist which has values greater than 3.

a <- c(1, 2, 3) 
b <- c(4, 5, 6) 
c <- c(7, 8, 9) 
list.x <- list(a,b,c)
names(list.x) <- c('Foo', 'Foobar', 'Foobarred')

Expected output

[1] "Foobar" "Foobarred"

I have toyed around with lapply, but I cannot understand how to loop through the values and return the sublist names, rather than the values.

Upvotes: 0

Views: 59

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76412

I did it in steps.
First step, a simple use of sapply "a user-friendly version and wrapper of lapply by default returning a vector, matrix", if simplify = TRUE, the default.

sapply(list.x, function(x) any(x > 3))
#      Foo    Foobar Foobarred 
#    FALSE      TRUE      TRUE 

Step two. Since it also returns the names, I tried to see if which would keep them.

which(sapply(list.x, function(x) any(x > 3)))
#   Foobar Foobarred 
#        2         3 

It does, so step three, wrap names around it.

names(which(sapply(list.x, function(x) any(x > 3))))
#[1] "Foobar"    "Foobarred"

Upvotes: 4

Related Questions