Search code examples
rindexingunique

A non index-oriented way to search for unique values between two lists in R


Lets say I have a section of a list that looks like this:

aaa[[1]]
# [1] "A5-5,73"  "B3-4,73"  "E3-8,73"  "A1-8,73"  "C1-7,73"  "A1-2,73"  "C3-2,73"  "C1-1,73"

Lets say I have another list with a section that looks like this:

bbb[[1]]
# [1] "B3-4,73"  "C3-2,73"  "A5-5,73"  "A1-8,73"  "A1-2,73"  "A1-5,73"  "B1-1,73"  "C1-4,73"

Consider that I now run

which(aaa[[1]]!= bbb[[1]])

which returns

# [1]  1  2  3  5  6  7  8  

This is technically true, because the index [4] is the same in both aaa and bbb

What I would like to have returned is:

# [1] "C1-7,73"  "A1-2,73" "C1-1,73"

because these are the values of aaa that are not in bbb regardless of position. I would also be open to a solution that would just provide an index number, such as:

# [1] 5 6 8

Here is a reproducible example:

aaa <- vector("list")
aaa[[1]] <- c("A5-5,73",  "B3-4,73",  "E3-8,73",  "A1-8,73",
          "C1-7,73",  "A1-2,73",  "C3-2,73",  "C1-1,73")
bbb <- vector("list")
bbb[[1]] <- c("B3-4,73",  "C3-2,73",  "A5-5,73",  "A1-8,73",
          "A1-2,73",  "A1-5,73",  "B1-1,73",  "C1-4,73")

Solution

  • If you want to compare every element of the list aaa with the corresponding element bbb simply do.

    mapply(FUN = setdiff, x = aaa, y = bbb)
    

    While writing this I saw setdiff was mentioned already in the comments by @RichardScriven.