Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting common character strings from multiple vectors of different lengths

Tags:

r

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?

like image 294
guyabel Avatar asked May 30 '12 18:05

guyabel


1 Answers

Yes:

Reduce(intersect,list(a1,a2,a3))
like image 179
joran Avatar answered Oct 18 '22 00:10

joran