Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove elements in a component of a list that already appeared in earlier components in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading