Bulat
Bulat

Reputation: 6969

Matching vectors by last element

I am wondering how can I join list of vectors to a data.frame or just to vectors to append new item to each vector with a match.

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

It is worth noticing that if last item in lst matches several values in vc, vector is duplicated. Vector stays unchanged if it does not match values in vc

Upvotes: 2

Views: 68

Answers (2)

Marat Talipov
Marat Talipov

Reputation: 13304

Try this one:

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)

Upvotes: 4

989
989

Reputation: 12937

Here is my solution:

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)

Upvotes: 0

Related Questions