How to subset a list using another list?

怎甘沉沦 提交于 2019-12-06 15:02:22

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/22870937/how-to-subset-a-list-using-another-list

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