I'm still a little green to R. So bear with me.
I have a list of vectors and I would like to compare each vector in the list and then tack on the matching list to the end of the match one. I am looking for robust repeatable solution, regardless of number of vectors in the list.
So if I have a list (lst
) made of vectors:
lst <- list(c("a", "b"), c("b", "c"), c("e", "f"), c("c", "g"))
I want to get a list of vectors like this as a result:
[[1]]
[1] "a" "b" "c" "g"
[[2]]
[1] "e" "f"
So I've been able to make this work for a singular instance:
if(any(lst[[1]] %in% lst[[2]])){
c(lst[[1]], lst[[2]])
}
but now I'm trying to loop it over the entire list and this is what I have so far, but I'm a little stuck:
endmembers <- lapply(seq_along(lst), function(i,j){
x <- lst[[i]]
x2 <- lst[[j]]
if(any(x %in% x2)){
c(x, x2)
}
})