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

29,171

At least in this case

Lobs[!(Lobs %in% Lexp)]

gives you what you want.

Share:
29,171
Harlan
Author by

Harlan

@harlanh

Updated on July 09, 2022

Comments

  • Harlan
    Harlan almost 2 years

    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?

  • Marek
    Marek over 14 years
    You don't need plyr: Lobs[sapply(names(Lobs), function(x) !identical(Lobs[[x]], Lexp[[x]]))]
  • JD Long
    JD Long over 14 years
    I was just using the %in% function yesterday for debugging and was about the recommend that.
  • Chetan Arvind Patil
    Chetan Arvind Patil about 6 years
    .@Harlan - Is it possible to find the percentage difference between two list having same structure? I am trying to compare how much the expected differ from the observed?