Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: find out identical elements in a list

Tags:

list

r

I want to find identical elements from a list. For example, if the list elements are dataframes:

List1 <- list(A=data.frame(id=c("LA","WE","SE"),num=c(1,3,2)),
              B=data.frame(id=c("PO","TD","WW"),num=c(8,1,4)),
              C=data.frame(id=c("PO","TD","WW"),num=c(8,1,4)),
              D=data.frame(id=c("SS","FW","MW"),num=c(2,5,1)),
              E=data.frame(id=c("LA","WE","SE"),num=c(1,3,2)),
              G=data.frame(id=c("LA","WE","SE"),num=c(1,3,2)))

I want to have the following output:

List2 <- list(c("A","E","G"),c("B","C")) 
#i.e., A, E, G are identical. B and C are identical.

Is there an easy way to do this? Thanks!!!

like image 269
l0110 Avatar asked Sep 19 '25 20:09

l0110


2 Answers

You can try the code below

> unname(split(names(List1), unlist(lapply(List1, toString))))
[[1]]
[1] "A" "E" "G"

[[2]]
[1] "B" "C"

[[3]]
[1] "D"
like image 175
ThomasIsCoding Avatar answered Sep 21 '25 09:09

ThomasIsCoding


Another option for comparing entire data.frames is to hash them and compare the hashes

digests <- sapply(List1, digest::digest)
sets <- split(names(List1), digests)
unname(sets)
# [[1]]
# [1] "A" "E" "G"
# [[2]]
# [1] "D"
# [[3]]
# [1] "B" "C"
like image 42
MrFlick Avatar answered Sep 21 '25 10:09

MrFlick