简体   繁体   中英

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.

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. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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