最后一个元素匹配向量

时间:2016-05-24 23:42:58

标签: r list vector

我想知道我如何将向量列表连接到data.frame,或者只是向向量添加新项目到匹配的每个向量。

HELLO

值得注意的是,如果# list of vectors that should be extended with values from vp # based on last item match to vc lst <- list(c("a", "b", "c"), c("b", "d"), c("f", "e") ) vc <- c("c", "c", "d") vp <- c("k", "l", "m") # expected output: expect <- list (c("a", "b", "c", "k"), c("a", "b", "c", "l"), c("b", "d", "m"), c("f", "e")) 中的最后一项与lst中的多个值匹配,则向量会重复。如果它与vc

中的值不匹配,则矢量保持不变

2 个答案:

答案 0 :(得分:4)

试试这个:

L <- lapply(lst, function(v) vp[vc %in% v[length(v)]])
pv <- function(v1, v2) {
      if (length(v2) == 0) {
        list(v1)
      }
      else {
        lapply(v2, function(v) c(v1,v))
      }
}
L2 <- mapply(pv, lst, L)
unlist(L2, recursive=F)

答案 1 :(得分:0)

这是我的解决方案:

l=lapply(lst, function(v) vp[vc %in% v])
res=sapply(1:length(lst), function(i) 
        {
            x=lst[[i]]
            y=l[[i]]
            if (length(y)>0)
                sapply(1:length(y), function(j)  list(c(x, y[j])))
            else
                list(x)
        }
    )
unlist(res, recursive = FALSE)