Home > Enterprise >  R - Finding duplicates in list entries
R - Finding duplicates in list entries

Time:02-07

I am trying to figure out how to get duplicates out of list objects in R. So my example list:

examplelist <- list(a = c("blue", "red", "yellow"),
                    b = c("red", "black", "green"),
                    c = c("black", "green", "brown"))

What I would like to get as a result:

  1. duplicates: c("red", "black", "green")
  2. vector of all entries, without double entries: c("blue", "red", "yellow", "black", "green", "brown")

I was not able to find a function for that other than duplicated() which just checks my list objects in total but not the entries itselves.

Thank you for your help :)

CodePudding user response:

You can unlist first:

unlisted <- unlist(examplelist)
unlisted[duplicated(unlisted)]
#     b1      c1      c2 
#  "red" "black" "green" 

unlisted[!duplicated(unlisted)]
#      a1       a2       a3       b2       b3       c3 
#  "blue"    "red" "yellow"  "black"  "green"  "brown" 

If you only want the vector (without the names), use unname:

unlisted <- unname(unlist(examplelist))
  •  Tags:  
  • Related