Matching in the list of vectors with different lengths

I have two lists:

List1 <- list(c("toto", "titi"), c("tata"), c("toto", "tz", "tutu"))

List2 <- list(c("titi", "toto", "tutu"),
              c("tata", "trtr", "to", "tututu"),
              c("to", "titi", "tutu", "tyty"),
              c("titi", "tu", "tyty", "tete"),
              c("tktk", "ta"))

And I want to create a list of (matches) that has a similar structure as an object List1, except that the character vectors are replaced by a list of matching indices of the elements of the first level List2, this is for each line of each character of the character.

The relevant list I would like to get with examples List1and List2thus:

Matchings <- list(list(list(1), list(1,3,4)),
                  list(list(2)),
                  list(list(1), list(), list(1,3)))

I created the following code solution (which works, but too slow) with loops:

Matching_list <- lapply(List1, function(x) sapply(x, function(y) return(list())))

for (i in 1:length(List1)) {
  for (j in 1: length(List1[[i]])) {
    Matchings = list()
    for (k in 1: length(List2)) {
      if(any(List1[[i]][j] %in% List2[[k]])) {
        Matchings <- c(Matchings, k)
      }
      if(length(Matchings) != 0) {
        Matching_list[[i]][[j]] <- Matchings
      }
    }
  }
}

... but it's too slow for large lists. So I'm looking for a solution that would make this substance without loops as possible.

could you help me?

+4
1

:

inds <- rep(seq_along(List2), sapply(List2, length))
#[1] 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5
ls <- unlist(List2)
res <- 
relist(sapply(unlist(List1), function(a) as.list(inds[which(ls %in% a)])), skeleton=List1)

all.equal(Matchings, res)
#[1] TRUE

. , , , List1.

+2

Source: https://habr.com/ru/post/1674718/


All Articles