guyabel
guyabel

Reputation: 8366

Extracting common character strings from multiple vectors of different lengths

Is there function in R to find the common characters in multiple vectors (of different lengths). For example, if I have 3 vectors...

 a1 <- LETTERS[1:7]
 a2 <- LETTERS[4:8]
 a3 <- LETTERS[2:10]

a1
# [1] "A" "B" "C" "D" "E" "F" "G"
a2
# [1] "D" "E" "F" "G" "H"
a3
# [1] "B" "C" "D" "E" "F" "G" "H" "I" "J"

I can think of a messy solutions...

intersect(intersect(a1,a2),a3)
# [1] "D" "E" "F" "G"

Problem is, I have around 8 or 9 vectors. Is there a better way to this?

Upvotes: 11

Views: 3248

Answers (1)

joran
joran

Reputation: 173577

Yes:

Reduce(intersect,list(a1,a2,a3))

Upvotes: 12

Related Questions