Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get the difference between two R named lists?

Tags:

list

indexing

r

set

OK, I've got two named lists, one is "expected" and one is "observed". They may be complex in structure, with arbitrary data types. I want to get a new list containing just those elements of the observed list that are different from what's in the expected list. Here's an example:

Lexp <- list(a=1, b="two", c=list(3, "four"))
Lobs <- list(a=1, c=list(3, "four"), b="ni")
Lwant <- list(b="ni")

Lwant is what I want the result to be. I tried this:

> setdiff(Lobs, Lexp)
[[1]]
[1] "ni"

Nope, that loses the name, and I don't think setdiff pays attention to the names. Order clearly doesn't matter here, and I don't want a=1 to match with b=1.

Not sure what a good approach is... Something that loops over a list of names(Lobs)? Sounds clumsy and non-R-like, although workable... Got any elegant ideas?

like image 844
Harlan Avatar asked Sep 23 '09 22:09

Harlan


People also ask

How do you find the difference between two sets in R?

A data frame is a tabular data structure in R that consists of rows and columns. To calculate the difference between two data frames in R, use the setdiff() function.

What does named list () mean in R?

A list is an object in R Language which consists of heterogeneous elements. A list can even contain matrices, data frames, or functions as its elements. The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them.

How do I put two lists together in R?

combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists. Two lists to be combined.

How do I combine list elements in R?

Combine lists in R Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do. call functions. When combining the lists this way, the second list elements will be appended at the end of the first list.


1 Answers

At least in this case

Lobs[!(Lobs %in% Lexp)]

gives you what you want.

like image 154
Peter Avatar answered Oct 11 '22 10:10

Peter