I have a list with each component being a numeric vector. There are some common numbers in the components. Here is an example:
ls <- list(c(7, 4, 9), c(5, 9, 2, 19), c(3, 13, 4, 2))
Component 2 has its second element already appeared in component 1. Component 3 has its 3rd and 4th element already appeared in component 1 and 2, respectively. I want to remove the elements in later component that already appeared in earlier component. For the specific example, I want ls2 <- list(c(7, 4, 9), c(5, 2, 19), c(3, 13)).
I wish to write an R script that automatically executes the above task, which generalizes to other lists.
>Solution :
Use setdiff:
ls <- list(c(7, 4, 9), c(5, 9, 2, 19), c(3, 13, 4, 2))
foo <- function(x) {
for (i in seq_along(x)[-1]) {
x[[i]] <- setdiff(ls[[i]], unlist(ls[seq_len(i - 1)]))
}
x
}
ls2 <- foo(ls)
#[[1]]
#[1] 7 4 9
#
#[[2]]
#[1] 5 2 19
#
#[[3]]
#[1] 3 13