如何使用另一个列表对列表进行子集化? [英] How to subset a list using another list?

查看:134
本文介绍了如何使用另一个列表对列表进行子集化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,我想使用另一个列表对列表中的数据进行子集化.说,我有一个名为mylisthislist的列表:

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

> 

hislist

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

> hislist
$a
[1] 5 6

$b
[1] 7 8

我尝试使用lapply函数对mylist进行子集化

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?

推荐答案

我能想到的最直接的解决方案是使用mapply:

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

该功能与当前lapply方法中使用的功能没有太大不同.

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

这篇关于如何使用另一个列表对列表进行子集化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆