R:在列表中找出相同的元素

a6b3iqyw  于 2023-06-19  发布在  其他
关注(0)|答案(3)|浏览(104)

我想从列表中找到相同的元素。例如,如果列表元素是dataframe:

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)))

我希望得到以下输出:

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

有什么简单的方法吗?Thanks!

ijxebb2r

ijxebb2r1#

你可以试试下面的代码

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

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

[[3]]
[1] "D"
mwkjh3gx

mwkjh3gx2#

比较整个 Dataframe 的另一种选择是对它们进行散列,然后比较散列

digests <- sapply(List1, digest::digest)
sets <- split(names(List1), digests)
unname(sets)
# [[1]]
# [1] "A" "E" "G"
# [[2]]
# [1] "D"
# [[3]]
# [1] "B" "C"
oprakyz7

oprakyz73#

tidyverse框架中,您还可以enframe列表和group_by数据。

library(tidyverse)
enframe(List1) %>% 
  reframe(name = list(name), .by = value) %>% 
  pull(name)

# [[1]]
# [1] "A" "E" "G"
# 
# [[2]]
# [1] "B" "C"
# 
# [[3]]
# [1] "D"

相关问题