[R] all combinations of the elements of two vectors

David Winsemius dwinsemius at comcast.net
Mon Aug 29 17:49:49 CEST 2011


On Aug 29, 2011, at 9:15 AM, Campbell, Desmond wrote:

> Petr, Jorge, Daniel,
>
> Yes you could also use outer() instead of expand.grid().
> This is quite useful to know.
>
> Also I didn't know you could turn a matrix into a vector by setting  
> its dimensions to NULL like that. I always used as.vector( m ).
> And (as I've just discovered) you can use it to reconfigure the  
> matrix's shape to any that contains the same number of elements.

You can do that but it requires that you understand the ordering of  
matrices if you want to avoid scrambling your indices. Since you seem  
new to that concept, you should work through several small examples to  
make sure you understand the effects of dimensional coercion.

You should also look at the aperm function and the abind package.

-- 
David.
>
> Thanks very much one and all.
>
> Regards
> Desmond
>
>
> -----Original Message-----
> From: Petr PIKAL [mailto:petr.pikal at precheza.cz]
> Sent: 29 August 2011 07:24
> To: Campbell, Desmond
> Cc: r-help at R-project.org
> Subject: Odp: [R] all combinations of the elements of two vectors
>
> Hi
>>
>> Dear R-help readers,
>>
>> I'm sure this problem has been answered but I can't find the  
>> solution.
>>
>> I have two vectors
>> v1 <- c("a","b")
>> v2 <- c(1,2,3)
>> I want an easy way to produce every possible combination of v1, v2
> elements
>> Ie I want to produce
>> c("a1","a2","a3", "b1","b2","b3")
>
> Another option is
>
> z<-outer(x,y, paste, sep="")
> dim(z)<-NULL
>> z
> [1] "a1" "b1" "c1" "a2" "b2" "c2" "a3" "b3" "c3"
>
> which gives the result in different order
>
> or
>
> z<-as.vector(t(z))
>> z
> [1] "a1" "a2" "a3" "b1" "b2" "b3" "c1" "c2" "c3"
>
> Which gives you desired order.
>
> Regards
> Petr
>
>>
>> regards
>> Desmond
>>
>> Desmond Campbell
>> Dept of Biostatistics and Computing, Institute of Psychiatry (KCL),
>> PO Box 20, De Crespigny Park, Denmark Hill London, SE5 8AF
>>
>> Tel 020 7848 0309
>> Email D.Campbell at iop.kcl.ac.uk<mailto:D.Campbell at iop.kcl.ac.uk>
>>
>>
>>
>>   [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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.
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list