Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find elements from a list that are not present in another list in r

Tags:

r

I have two lists that have the same vectors but with different length

list1 <- list(a = 1:10, b = 3:20)
list2 <- list(a = c(2,5,8), b = c(3,5,11,20))

I would like to find elements from each vector in list1 that are not present in the corresponding vector in list2. There are similar questions answered for other scripts instead of R.

I expect the final list is

lst <- list(a=c(1,3,4,6,7,9,10),b=c(4,6:10,12:19))

Thank you for help.

like image 857
user3354212 Avatar asked Sep 01 '16 17:09

user3354212


People also ask

How to get all the elements of a vector in R?

If we want all the elements of a vector that are not in another vector then we can use setdiff () method in R. It takes two vectors and returns a new vector with the elements of the first vector that are not present in the second vector.

How to find all elements of a list that are not in?

Write a R program to find all elements of a given list that are not in another given list. l1 = list("x", "y", "z") l2 = list("X", "Y", "Z", "x", "y", "z") print("Original lists:") print( l1) print( l2) print("All elements of l2 that are not in l1:") setdiff ( l2, l1)

How to find items in one list that are not in another?

How to find items in one list that are not in another list in C#? The Except () method requires two collections and find those elements which are not present in second collection Except extension method doesn't return the correct result for the collection of complex types.

How many list elements are in a list in RStudio?

Let’s dive right in! The previous output of the RStudio console shows that our example data is a list with four list elements. In this section, I’ll show how to identify the index positions of all list elements that contain a particular value.


1 Answers

We can use

mapply(setdiff,list1,list2)
#$a
#[1]  1  3  4  6  7  9 10

#$b
#[1]  4  6  7  8  9 10 12 13 14 15 16 17 18 19
like image 155
Zheyuan Li Avatar answered Sep 28 '22 03:09

Zheyuan Li