Maik
Maik

Reputation: 182

Filter different values in each list using vectorized functions

I have a list:

> list
[[1]]
 [1] 5 3 7 9 3 8 3 4 5 7

[[2]]
 [1] 2 8 7 8 7 9 6 3 1 4

[[3]]
 [1] 7 2 1 7 9 8 9 8 8 2

[[4]]
 [1]  5  2  2  1  8  8  2  1 10  7

And now I have a list of elements that I want to filter.

> filtering
[[1]]
 [1] 11 10 12

[[2]]
 [1] 7 3 9

[[3]]
 [1] 3 7 8

[[4]]
 [1] 2 6 9

I want to filter, without using any looping, list[[1]] with elements in filtering[[1]], then elements from list[[2]] with elements in filtering[[2]], etc...

Upvotes: 2

Views: 51

Answers (1)

zx8754
zx8754

Reputation: 56179

Something like this (but mapply is still a loop):

# example data
mylist <- list(1:5, 11:15)
myfilter <- list(c(2,4), c(12, 13))


mapply(FUN = function(x, y){ x[ x %in% y] }, mylist, myfilter, SIMPLIFY = FALSE)
# [[1]]
# [1] 2 4
# 
# [[2]]
# [1] 12 13

Or as suggested in the comments by @akrun, using purrr package:

library(purrr)

map2(mylist, myfilter, ~ .x[.x %in% .y])

Upvotes: 4

Related Questions