How to subset a list using another list?

大憨熊 提交于 2019-12-04 20:02:40

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.

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!