[R] give all combinations
baptiste auguie
ba208 at exeter.ac.uk
Sun Aug 31 12:56:58 CEST 2008
I had a similar problem recently where I used the following code:
> v <- factor(letters[1:3])
> all.cases <- expand.grid(v, v)
> all.cases[as.numeric(all.cases[, 2]) >= as.numeric(all.cases[, 1]), ]
I'm not sure how to extend it cleanly to an arbitrary number of
vectors, though.
Baptiste
On 31 Aug 2008, at 11:18, Peter Dalgaard wrote:
> Lucien Lemmens wrote:
>> Yuan Jian <jayuan2008 <at> yahoo.com> writes:
>>
>>
>>> Hello,
>>> is there a simple way to give all combinations for a given vector:
>>> v<-c("a","b","c")
>>> combination(v,v) becomes
>>> "aa","ab","ac","bb","bc","cc'
>>> combination(v,v,v) becomes
>>> "aaa","aab","aac","abb",......
>>>
>> vv<-c(outer(v,v,paste))
>> vv
>> [1] "a a" "b a" "c a" "a b" "b b" "c b" "a c" "b c" "c c"
>> vvv<-c(outer(vv,v,paste)
>> vvv
>> [1] "a a a" "b a a" "c a a" "a b a" "b b a" "c b a" "a c a" "b c a"
>> "c c a" "a a b" "b a b" "c a b" "a b b" "b b b" "c b b"
>> [16] "a c b" "b c b" "c c b" "a a c" "b a c" "c a c" "a b c" "b b
>> c" "c b c" "a c c" "b c c" "c c c"
>>
>>
> Notice that "ca" was not in the request for combination(v,v), so
> it's a bit trickier. I was thinking ?combn, but that doesn't count
> the duplicated cases:
>
> > combn(v,2)
> [,1] [,2] [,3]
> [1,] "a" "a" "b"
> [2,] "b" "c" "c"
>
>
> --
> O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
> c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
> (*) \(*) -- University of Copenhagen Denmark Ph: (+45)
> 35327918
> ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45)
> 35327907
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
_____________________________
Baptiste Auguié
School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK
Phone: +44 1392 264187
http://newton.ex.ac.uk/research/emag
More information about the R-help
mailing list