Reputation: 8824
I have a couple of vectors consisting of three names. I want to get all unique pairwise combinations of these vectors. As an example, with two of those vectors, I can get the non-unique combinations with
sham1 <- c('a', 'b')
sham2 <- c('d', 'e')
shams <- list(sham1, sham2)
combinations <- apply(expand.grid(shams, shams),1, unname)
which gives the following combinations
> dput(combinations)
list(
list(c("a", "b"), c("a", "b")),
list(c("d", "e"), c("a", "b")),
list(c("a", "b"), c("d", "e")),
list(c("d", "e"), c("d", "e"))
)
I tried using unique(combinations)
, but this gives the same result. What I would like to get is
> dput(combinations)
list(
list(c("a", "b"), c("a", "b")),
list(c("d", "e"), c("a", "b")),
list(c("d", "e"), c("d", "e"))
)
Because there is already the combination list(c("d", "e"), c("a", "b"))
, I don't need the combination list(c("a", "b"), c("d", "e"))
How can I get only the unique combination of vectors?
Upvotes: 1
Views: 1191
Reputation: 58825
combn
gets you the combinations (so, unique), but not the repeated ones. So combine that with something that gives you the repeated ones and you have it:
c(combn(shams, 2, simplify=FALSE),
lapply(shams, function(s) list(s,s)))
Upvotes: 1
Reputation: 44614
s <- seq(length(shams))
# get unique pairs of shams indexes, including each index with itself.
uniq.pairs <- unique(as.data.frame(t(apply(expand.grid(s, s), 1, sort))))
# V1 V2
# 1 1 1
# 2 1 2
# 4 2 2
result <- apply(uniq.pairs, 1, function(x) shams[x])
Upvotes: 1
Reputation: 4220
I am also not exactly sure what you want but this function might help:
combn
Here is a simple example:
> combn(letters[1:4], 2)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a" "a" "a" "b" "b" "c"
[2,] "b" "c" "d" "c" "d" "d"
I don't think this is what you want, but if you clarify perhaps I can edit to get you what you want:
> sham1<-c('a','b')
> sham2<-c('d','e')
> combn(c(sham1,sham2),2)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "a" "a" "a" "b" "b" "d"
[2,] "b" "d" "e" "d" "e" "e"
Upvotes: 1
Reputation: 3397
I don't understand what do you want. And it seems that you changed the desired output from your other question.
You want your two list nested in a list inside another list???
It is not simpler to just once? Like when you have shams
?
dput(shams)
list(c("Sham1.r1", "Sham1.r2", "Sham1.r3"), c("Sham2.r1", "Sham2.r2",
"Sham2.r3"))
To create such a nested list you could use that:
combinations <- list(shams, "")
dput(combinations)
list(list(c("Sham1.r1", "Sham1.r2", "Sham1.r3"), c("Sham2.r1", "Sham2.r2",
"Sham2.r3"), "")
Although it is not exactly what do you said...
Upvotes: 0
Reputation: 57686
No idea what your examples are saying. If you want unique pairwise combinations:
strsplit(levels(interaction(sham1, sham2, sep="*")), "\\*")
Upvotes: 0