Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

r - Finding all possible combinations of vector intersections?

I have a set of four vectors that look like this:

[1] PRI2CO       HEISCO       PRI2CO       DIALGU       DIALGU       ALSEBL      
Levels: ALSEBL       DIALGU       HEISCO       PRI2CO  

[1] PRI2CO       TET2PA       ALSEBL       PRI2CO       ALSEBL       TET2PA      
[7] HEISCO       TET2PA      
Levels: ALSEBL       HEISCO       PRI2CO       TET2PA

I would like to generate a vector that contains all values that match between every possible combination of the four vectors. For the two above, it would contain ALESBL, HEISCO, and PRI2CO. I've been doing every combination by hand so far but its tedious and I figure there has to be a better way. I tried writing a loop for it but I'm pretty new to R and it hasn't worked yet. Here's what I've been doing:

trees.species.P234<-intersect(intersect(trees.species.P2,trees.species.P3),trees.species.P4)
> trees.species.P234
[1] "PRI2CO      " "ALSEBL      "

I was thinking a for loop that involved a factorial might do it, but I can't get it to work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here you go, using the same vectors as proposed by gadzooks:

v1 <- c("PRI2CO","HEISCO","PRI2CO","DIALGU","DIALGU","ALSEBL")
v2 <- c("PRI2CO", "TET2PA","ALSEBL","PRI2CO","ALSEBL","TET2PA","HEISCO","TET2PA")
v3 <- c("PRI2CO","HEISCO","PRI2CO","DIALGU","DIALGU","ALSEBL")
v4 <- c("PRI2CO", "TET2PA","ALSEBL","PRI2CO","ALSEBL","TET2PA","HEISCO","TET2PA")

veclist <- list(v1,v2,v3,v4)
combos <- Reduce(c,lapply(2:length(veclist), 
            function(x) combn(1:length(veclist),x,simplify=FALSE) ))

lapply(combos, function(x) Reduce(intersect,veclist[x]) )

#[[1]]
#[1] "PRI2CO" "HEISCO" "ALSEBL"
# 
#[[2]]
#[1] "PRI2CO" "HEISCO" "DIALGU" "ALSEBL"
#
#[[3]]
#[1] "PRI2CO" "HEISCO" "ALSEBL"
#etc etc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...