简体   繁体   English

如果未在列表之间共享,则从列表中删除项

[英]Remove items from list if not shared between lists

Some example data 一些示例数据

 List1 = list("Jake009", "Sarah0390", "Tom_338", "Philip-478")
 List2 = list("Jake__98", "Sarah//43", "Brett-49")

I want to remove all items from list one that don't have a match in list 2. 我想删除列表2中列表2中没有匹配项的所有项目。

So the code would need to examine, in both lists, each string up to the first non-alphabetic character (eg, "Jake" ) and see if there is a match in the other list. 因此,代码需要在两个列表中检查每个字符串,直到第一个非字母字符(例如,“Jake”)并查看另一个列表中是否存在匹配。 If not, remove it from the list. 如果没有,请从列表中删除它。

Goal: 目标:

 List1 = "Jake009", "Sarah0390"
 List2 = "Jake__98", "Sarah//43"

We remove the non-alphabet characters with sub in both lists and use %in% to get the logical index of elements present in one with respect to other. 我们使用两个lists sub删除非字母字符,并使用%in%来获取元素相对于其他元素的逻辑索引。

v1 <- sub('[^A-Za-z]+$', '', unlist(List1))
v2 <-  sub('[^A-Za-z]+$', '', unlist(List2))
List1[v1 %in% v2]
#[[1]]
#[1] "Jake009"

#[[2]]
#[1] "Sarah0390"

List2[v2 %in% v1]
#[[1]]
#[1] "Jake__98"

#[[2]]
#[1] "Sarah//43"

Or using intersect as suggested by @Frank 或者用intersect通过@Frank的建议

vv1 <- setNames(List1,v1)
vv2 <- setNames(List2,v2)
both <- intersect(names(vv1),names(vv2))
vv1[both]
vv2[both]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM