Remove items from a list if they are not split between lists

Some sample data

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

      

I want to remove all items from a list that do not have a match in list 2.

So the code would have to check each line in both lists up to the first non-alphabetic character (like "Jake") and see if there is a match in the other list. If not, remove it from the list.

Purpose:

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

      

+3


source to share


1 answer


We strip the non-alphabetic characters from sub

in lists

and use it %in%

to get the logical index of the elements present in one relative to the 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]

      

+3


source







All Articles