Shand
Shand

Reputation: 51

how to filter a list in R

I have a list that I want to filter.

[[100]][[1]]$total
[1] 7


[[100]][[2]]
[1] 7

[[100]][[3]]
[1] 25082.66

this is the output I get from my script, I am trying to filter all elements from this list where total = 7. I have a total of 100 elements.

my list is labelled as sorts

 A<-(list.filter(sorts,total>6)) 

I want to have a list with only elements where total is 7

Upvotes: 4

Views: 4530

Answers (2)

akrun
akrun

Reputation: 887028

We can use pluck and map

keep(lst, map(lst, pluck, "total") == 7)
#[[1]]
#[[1]]$total
#[1] 7

#[[1]][[2]]
#[1] 2

#[[1]][[3]]
#[1] 2


#[[2]]
#[[2]]$total
#[1] 7

#[[2]][[2]]
#[1] 2

#[[2]][[3]]
#[1] 2

data

lst <- list(list(total = 100, 1, 2), list(total = 7, 2, 2), 
        list(total = 7, 2, 2), list(total = 71, 2, 2))

Upvotes: 6

Ronak Shah
Ronak Shah

Reputation: 388862

We can extract "total" element from each list and select only those elements with 7 in it.

lst[sapply(lst, "[[", "total") == 7]

#[[1]]
#[[1]]$total
#[1] 7

#[[1]][[2]]
#[1] 2

#[[1]][[3]]
#[1] 2


#[[2]]
#[[2]]$total
#[1] 7

#[[2]][[2]]
#[1] 2

#[[2]][[3]]
#[1] 2

Or we can also use Filter

Filter(function(x) x[["total"]] == 7, lst)

Using purrr we can use keep/discard

library(purrr)
keep(lst, ~.[["total"]] == 7)

discard(lst, ~.[["total"]] != 7)

Or map_lgl

lst[map_lgl(lst, ~.[["total"]] == 7)]

data

Assuming your list is called lst and looks like the following

lst <- list(list(total = 100, 1, 2), list(total = 7, 2, 2), 
        list(total = 7, 2, 2), list(total = 71, 2, 2))

Upvotes: 9

Related Questions