匹配具有不同长度的向量列表

我有两个这样的列表:

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"))

我想构建一个(匹配的)列表,它具有与List1对象类似的结构,除了字符向量被List2的第一级元素的匹配索引列表替换,这对于每个字符的每个字符串向量.

我将通过list1和list2示例获得的匹配列表是:

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

我用循环构建了以下代码解决方案(可行,但速度太慢):

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

……但对于大型名单来说,它确实太慢了.因此,我寻求一种解决方案,尽可能使这些东西没有循环.

你可以帮帮我吗?

最佳答案 这个怎么样:

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上循环.

点赞