[R] Combining characters

Marc Schwartz marc_schwartz at me.com
Wed Jan 4 22:49:41 CET 2012


On Jan 4, 2012, at 10:32 AM, jeremy wrote:

> Hi all,
> 
> I'm trying to combine exhaustively several character arrays in R like:
> x=c("one","two","three")
> y=c("yellow","blue","green")
> z=c("apple","cheese")
> 
> in order to get concatenation of 
> 
> x[1] y[1] z[1]  ("one yellow apple")
> x[1] y[1] z[2] ("one yellow cheese")
> x[1] y[2] z[1]("one blue apple")
> ...
> x[length(x)] y[length(y)] z[length(z)]  ("three green cheese")
> 
> Anyone has a solution ?
> Thank in advance


See ?expand.grid and ?paste

DF <- expand.grid(x, y, z)

> DF
    Var1   Var2   Var3
1    one yellow  apple
2    two yellow  apple
3  three yellow  apple
4    one   blue  apple
5    two   blue  apple
6  three   blue  apple
7    one  green  apple
8    two  green  apple
9  three  green  apple
10   one yellow cheese
11   two yellow cheese
12 three yellow cheese
13   one   blue cheese
14   two   blue cheese
15 three   blue cheese
16   one  green cheese
17   two  green cheese
18 three  green cheese


> with(DF, paste(Var1, Var2, Var3))
 [1] "one yellow apple"    "two yellow apple"    "three yellow apple" 
 [4] "one blue apple"      "two blue apple"      "three blue apple"   
 [7] "one green apple"     "two green apple"     "three green apple"  
[10] "one yellow cheese"   "two yellow cheese"   "three yellow cheese"
[13] "one blue cheese"     "two blue cheese"     "three blue cheese"  
[16] "one green cheese"    "two green cheese"    "three green cheese" 

HTH,

Marc Schwartz



More information about the R-help mailing list