Jeremy
Jeremy

Reputation: 876

Find shared elements in a list

I can find the shared elements from each data in a small list. A simplified example is here:

data_1 <- c("A","B")
data_2 <- c("A","B","C")
data_3 <- c("A","B","C","D")
data_4 <- c("A","B","F","N")

list.a <- list(data_1,data_2,data_3,data_4)

# find common elements
shared <- Reduce(intersect, list(list.a[[1]], list.a[[2]], list.a[[3]]), list.a[[4]]))  

# outputs
print(shared)                 
[1] "A" "B"           

But the problem in real work is: The list is really large, say it contains 100 data, then this approach is not efficient anymore, and may introduce mistakes. Is there a way to avoid listing all of themlist(list.a[[1]], list.a[[2]], list.a[[3]]), list.a[[4]])? Something short and neat.

Upvotes: 1

Views: 270

Answers (2)

akrun
akrun

Reputation: 886968

Here, is another option with reduce

library(purrr)
library(dplyr)
list.a %>%
      reduce(intersect)

Upvotes: 0

jay.sf
jay.sf

Reputation: 72633

Just use your list rather than listing its sub-elements.

(shared <- Reduce(intersect, list.a))
# [1] "A" "B"

Upvotes: 2

Related Questions