[R] all combinations of the elements of two vectors

Campbell, Desmond desmond.d.campbell at kcl.ac.uk
Sat Aug 27 20:27:28 CEST 2011


Dear Jorge

Yes expand.grid() is exactly what I wanted.
This problem keeps cropping up, and I've never known a simple way to implement it.

Thanks very much.

Regards
Desmond

________________________________________
From: Jorge I Velez [mailto:jorgeivanvelez at gmail.com] 
Sent: 27 August 2011 19:19
To: Campbell, Desmond
Cc: r-help at R-project.org
Subject: Re: [R] all combinations of the elements of two vectors

Hi Desmond,


You might try

> sort(apply(expand.grid(v1, v2), 1, paste, collapse = "", sep = ""))
[1] "a1" "a2" "a3" "b1" "b2" "b3"

HTH,
Jorge


On Sat, Aug 27, 2011 at 12:54 PM, Campbell, Desmond <> wrote:
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")

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.



More information about the R-help mailing list