vendredi 31 juillet 2020

R: Cross reference vector with list, HELP: append new vector based on positive hits

I have a vector A and a list B of vectors ls1, ls2 and ls3. I aim to combine the vectors in list B that contain one or more of the entries of A into a new vector (new_v).

A <- c("cat", "dog", "bird")
A

B <- list(v1 = c("mike", "fred", "paul"), v2 = c("mouse", "cat", "frog"), v3 = c("bird", "cow", "snake"))
B

new_list <- c()

for(i in names(B)){
  
  v <- A %in% B[[i]]
  print(v)
  
  if (TRUE %in% v){
    
    append(new_v, unlist(B[i])) ## doesn't do what I want
    
  }
}
print(new_v)

The result I was hoping for:

>dput(new_v)
c("mouse", "cat", "frog", "bird", "cow", "snake")

Aucun commentaire:

Enregistrer un commentaire