Question

I have two lists and I want to subset data in a list using another list. Say, I have lists called mylist and hislist:

mylist <- list(a = data.frame(cola = 1:3, colb = 4:6), 
           b = data.frame(cola = 1:3, colb = 6:8))
> mylist
$a
  cola colb
1    1    4
2    2    5
3    3    6

$b
  cola colb
1    1   6
2    2   7
3    3   8

> 

and hislist

hislist <- list(a = 5:6, 
                b = 7:8)

> hislist
$a
[1] 5 6

$b
[1] 7 8

I tried to subset mylist using lapply function:

lapply(mylist, function(x) subset(x, colb %in% hislist))
#or
lapply(mylist, function(x) x[x$colb %in% hislist,])

but these does not work. How to solve this issue?

Was it helpful?

Solution

The most straightforward solution I can think of is to use mapply:

mapply(function(x, y) x[x[, 2] %in% y,], mylist, hislist, SIMPLIFY=FALSE)
# $a
#   cola colb
# 2    2    5
# 3    3    6
# 
# $b
#   cola colb
# 2    2    7
# 3    3    8

The function is not much different than what you use in your current lapply approaches.

OTHER TIPS

In your particual example just use unlist for hislist, which will make it a vector of values.

lapply(mylist, function(x) x[x$colb %in% unlist(hislist),])
$a
  cola colb
2    2    5
3    3    6

$b
  cola colb
2    2   11
3    3   12
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top