paste grid -- expand.grid for string concatenation

combinations, r, string-concatenation

Solution

Yes, this is what `interaction` does

levels(interaction(x,y,z,sep='_'))

The implementation is pretty much the same as your `rep` code.

Outputs:

[1] "avg_female_height"    "median_female_height" "avg_male_height"      "median_male_height"   "avg_female_weight"   
[6] "median_female_weight" "avg_male_weight"      "median_male_weight"  

Problem

If we want to get all combinations of two vectors, we can use `rep`/recycling rules: ``` x <- 1:4 y <- 1:2 cbind(rep(x, each = length(y)), rep(y, length(x))) # [,1] [,2] # [1,] 1 1 # [2,] 1 2 # [3,] 2 1 # [4,] 2 2 # [5,] 3 1 # [6,] 3 2 # [7,] 4 1 # [8,] 4 2 ``` But `expand.grid` is much nicer -- it handles all the repetition for us. ``` expand.grid(x, y) # Var1 Var2 # 1 1 1 # 2 2 1 # 3 3 1 # 4 4 1 # 5 1 2 # 6 2 2 # 7 3 2 # 8 4 2 ``` Is there a simple version of this for concatenating strings? Like `paste.grid`? I have a named object where a lot of the objects have names like `x_y_z` where `x`, `y`, and `z` vary like `x` and `y` above. For example, suppose `x` can be `"avg"` or `"median"`, `y` can be `"male"` or `"female"`, and `z` can be `"height"` or `"weight"`. How can we concisely get all 8 combinations of the three? Using `rep` is a pain: ``` x <- c("avg", "median") y <- c("male", "female") z <- c("height", "weight") paste(rep(x, each = length(y) * length(z)), rep(rep(y, each = length(z)), length(x)), rep(z, length(x) * length(y)), sep = "_") ``` And repurposing `expand.grid` is a bit clunky (and probably inefficient): ``` apply(expand.grid(x, y, z), 1, paste, collapse = "_") ``` Am I missing something? Is there a better way to do this?

Original source