确定列表的哪些对象包含在R中的另一个列表中(子集) [英] Identify which objects of list are contained (subset of) in another list in R

查看:39
本文介绍了确定列表的哪些对象包含在R中的另一个列表中(子集)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谢谢您对我之前的问题的答复.我有两个列表:list1和list2.我想知道list1的每个对象中是否包含list1的每个对象.例如:

Thank you for your kind reply to my previous questions. I have two lists: list1 and list2. I would like to know if each object of list1 is contained in each object of list2. For example:

> list1
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

> list2
[[1]]
[1] 1 2 3

[[2]]
[1] 2 3

[[3]]
[1] 2 3

这是我的问题:1.)我如何要求R检查对象是否为列表中另一个对象的子集?例如,我想检查 list1 [[2]] = {2} list2 [[3]] = {2,3} >.当我执行 list2 [[3]]%in%list1 [[2]] 时,我得到 [1]真错误.但是,这不是我想要做的吗?!我只想检查 list2 [[3]] 是否是 list1 [[2]] 的子集,即{2,3} \ {3}的子集像定论理论中一样?我不想执行元素检查,因为R似乎正在使用%in%命令.有什么建议吗?

Here are my questions: 1.) How do you I ask R to check if an object is a subset of another object in a list? For instance I would like to check if list2[[3]]={2,3} is contained in (subset of) list1[[2]]={2}. When I do list2[[3]] %in% list1[[2]], I get [1] TRUE FALSE. However, this is not what I desire to do?! I just want to check if list2[[3]] is a subset of list1[[2]], i.e. is {2,3} \subset of {3} as in the set theoretic notion? I do not want to perform elementwise check as R seems to be doing with the %in% command. Any suggestions?

2.)是否存在某种有效地进行所有成对子集比较的方法(即, list2 [[j]] list1 [[i]] 子集,对于所有 i,j 组合,一旦问题1回答后,类似 outer(list1,list2,func.subset)的东西就会起作用吗?谢谢您的反馈!

2.) Is there some sort of way to efficiently make all pairwise subset comparisons (i.e. list1[[i]] subset of list2[[j]], for all i,j combinations? Would something like outer(list1,list2, func.subset) work once question number 1 is answered? Thank you for your feedback!

推荐答案

setdiff 比较唯一

length(setdiff(5, 1:5)) == 0

或者, all(x%in%y)会很好地工作.

要进行所有比较,可以使用以下方法:

To do all comparisons, something like this would work:

dt <- expand.grid(list1,list2)
dt$subset <- apply(dt,1, function(.v) all(.v[[1]] %in% .v[[2]]) )


  Var1    Var2 subset
1    1 1, 2, 3   TRUE
2    2 1, 2, 3   TRUE
3    3 1, 2, 3   TRUE
4    1    2, 3  FALSE
5    2    2, 3   TRUE
6    3    2, 3   TRUE
7    1    2, 3  FALSE
8    2    2, 3   TRUE
9    3    2, 3   TRUE

请注意, expand.grid 不是处理大量数据时最快的方法(在这方面dwin的解决方案更好),但是它允许您快速地目视检查是否这就是您想要的.

Note that the expand.grid isn't the fastest way to do this when dealing with a lot of data (dwin's solution is better in that regard) but it allows you to quickly check visually whether this is doing what you want.

这篇关于确定列表的哪些对象包含在R中的另一个列表中(子集)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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